I am trying to write NSString to the file. It is writing successfully however I want to append the new string to new line.
How can do this?
You can read file content, append new data to that content and save new data to a file you use:
// Here you set your appending text.
NSString *yourAppendingText = #"yourAppendingText";
// Here you get access to the file in Documents directory of your application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *documentFile = [documentDir stringByAppendingPathComponent:#"yourFile.txt"];
// Here you read current existing text from that file
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil];
// Here you append new text to the existing one
NSString *textToFile = [textFromFile stringByAppendingString:yourAppendingText];
// Here you save the updated text to that file
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
Related
I want to create a document based application in Xcode. It's a note app. People can create their notes file. It's a basic app, because I'm trying to learn how you can save and load data in a document based application. I'm not trying to save a tableview, I'm trying to save and load the stringValue of a TextField.
So, how do you save and load a NSString in a document based app in Objective-C (Xcode)?
You can use NSString's writeToFile:atomically:encoding:error:
and stringWithContentsOfFile:encoding:error: methods.
Here's an example of how to write to a file:
NSString *fileName = "myNote.txt";
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = dirPaths[0];
NSString *filePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:fileName]];
[myString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&myError];
Or if you want something advanced, you can use Core Data.
I am new to iPhone development.I am working on project where i have to create .csv file in application locally and view it within the application itself. I have succeed in creating the .csv file and savig it in document directory.But problem is that i dont know how do i view that .csv excel within the application after creating.Any suggestion is welcome.
Thanks.
I assume u might be saving csv in document directory.U can use UIWebView to display your csv content like this;
NSString *filePath = [self documentsDirectoryPath];
filePath = [filePath stringByAppendingPathComponent:#"file.csv"]; //your saved fileName
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
[yourWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
}
Get document directory path like this:
- (NSString *)documentsDirectoryPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
return documentsDirectoryPath;
}
I have some data in a .txt file that I dragged over to resources in xcode 4.2. I then use some methods that call upon this file, read it, and display it on the screen to the user. It works. My problem is writing to the end of the same file (aka updating the file based on something the user did) directly on the iphone/ the simulator. It does not write for I feel I am not calling upon the right location and perhaps method. This is my code to write to the end of file, if anyone knows why this is not working it would be tremendous help.
Thank you
-(void)updateFile:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//append filename to docs directory
NSString *myPath = [documentsDirectory stringByAppendingPathComponent:#"Mom.txt"];
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:myPath];
dateCombinedString= [dateCombinedString lowercaseString];
writtenString= [[NSString alloc]initWithFormat:#", %#, %#, %#",dateString,trimmedString,ForDisplay];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[writtenString dataUsingEncoding:NSUTF8StringEncoding]];
[writtenString release]
}
The file you dragged to Xcode is inside your app resources. You can get the path to resource with this line of code:
NSURL* fileUrl = [[NSBundle mainBundle] URLForResource:#"Mom" withExtension:#"txt"];
However, you cannot modify the files in the resource directory therefore you should first copy that file to your document directory, then modify it with the code in the question.
Here is how you can copy file from resources if the file does not exist on the documents folder:
NSFileManager* fm;
fm = [NSFileManager defaultManager];
//only copy it from resources if it does not exits
if(![fm fileExistsAtPath:myPath]){
NSURL* myUrl = [NSURL fileURLWithPath:myPath];;
NSError* error = nil;
[fm copyItemAtURL:fileUrl toURL:myUrl error:&error];
//handle the error appropriately
}
I'm trying to create a text file with the contents of a string to my desktop. I'm not sure if I'm doing it right, I don't get errors but it doesn't work either...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory=[paths objectAtIndex:0];
NSString *filename = [desktopDirectory stringByAppendingString: #"file.txt"];
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL];
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
You don't know if you're getting any errors because you're ignoring the returned YES/NO value of the -writeToFile:... method, and giving it no error pointer into which to record any possible failure. If the method returns NO, you'd check (and handle or present) the error to see what went wrong.
At a guess, the failure is due to the path you constructed. Try -stringByAppendingPathComponent: instead of -stringByAppendingString: ... this and its related methods properly handle paths.
The file probably is actually being created (ie, you might not be getting any errors after all). My guess is the file is created somewhere like "~/Desktopfile.txt" since your use of -stringByAppendingString: doesn't consider the string as slash-separated path. Check your home folder - I'll bet the file's there.
the problem is that the desktop directory string ends in nothing (no /). Check this out (on an iPhone) by using UIAlertview.
I'm new to mac and Cocoa so I'm sorry if this is a stupid question..
I need to read all the lines I wrote on a file I saved on my desktop.
The file format is .txt; I tried with stringWithContentsOfFile but the program freezes.
I tried with GDB and I noticed that, while the path is correct, the string which is supposed to contain the data returns nil.
Am I missing something important?
You need to use a path not just the filename
NSString *string;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] != 0) {
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *newFile = [documentsDirectory stringByAppendingPathComponent:#"filename.txt"];
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:newFile]) {
string = [NSString stringWithContentsOfFile:newFile];
}
}
You will need to replace the documents directory for the bundle directory if you are reading from there.
EDIT
I jumped the gun. It seems that this is NOT an iPhone question. None-the-less, you will need to pass in the full path, not just the filename