About 2000 strings to a file - iphone

I need to put separate lines into a file, but it seems that it's not supported by
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"myFile"];
[dataString writeToFile:appFile atomically:YES];
It does put a string to a file but it overwrites previous one.
Any suggestions?

To append data to an existing file, create an NSFileHandle instance for that file, then call -seekToEndOfFile and finally -writeData:. You'll have to convert your string into an NSData object yourself (with the correct encoding). And don't forget to close the file handle when you're finished.
The easier, but also less efficient way, is to read the existing file contents into a string, then append the new text to that string and write everything out to disk again. I wouldn't do that in a loop that executes 2000 times, though.

Thanks Ole! That's what I've been looking for.
Some sample code for the others:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//creating a path
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"nameOfAFile"];
//clearing or creating (NSFileHande doesn't support creating a file it seems)
NSString *nothing = #""; //remember it's CLEARING! so get rid of it - if you want keep data
[nothing writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
//creating NSFileHandle and seeking for the end of file
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:appFile];
[fh seekToEndOfFile];
//appending data do the end of file
NSString *dataString = #"All the stuff you want to add to the end of file";
NSData *data = [dataString dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];
//memory and leaks
[fh closeFile];
[fh release];
[dataString release];

Related

save pdf file in device

I generated a pdf file in my program and I have it here :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingFormat:#"/CEX.pdf"];
NSData *data = [NSData dataWithContentsOfFile:file];
I know how to save photos in the photo gallery but have no idea what should I do with pdf file and how and where to save it in the device. Can anyone help me please ?! :)
The code you posted is for reading an existing PDF file from the Documents directory.
If you want to write the PDF, you need to get the NSData object representing the PDF, create a path to the file, then use the NSData writeToFile:options:error: method to save the data to the file.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingPathComponent:#"MyDocument.pdf"];
NSData *pdfData = ... // data representing your created PDF
NSError *error = nil;
if ([pdfData writeToFile:file options:NSDataWritingAtomic error:&error]) {
// file saved
} else {
// error writing file
NSLog(#"Unable to write PDF to %#. Error: %#", file, error);
}
BTW - in your original code, replace:
NSString *file = [documentsDirectory stringByAppendingFormat:#"/CEX.pdf"];
with:
NSString *file = [documentsDirectory stringByAppendingPathComponent:#"CEX.pdf"];
Don't use string formats unless you really have a string format to process.

Saving Data from iphone app to text file in iPhone app

I want to save my application data in text file in documents folder
I am using following way to store but it store single string i want that my data is in array how may store all the contents of array in text files
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString*yourString=#"This is working fine";
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"file.txt"];
NSString *stringWithoutSpaces = [yourString stringByReplacingOccurrencesOfString:#" " withString:#""];
[stringWithoutSpaces writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
My Array is like Following
DataController *coffeeObj = [appDelegate.coffeeArray objectAtIndex:indexPath.row];
cell.resturantLocationLabel.text=coffeeObj.resturantLocation;
cell.foodQualityRatingLabel.text=coffeeObj.foodQualityRating;
cell.foodPresentationRatingLabel.text=coffeeObj.foodPresentationRating;
cell.waiterRatingLabel.text=coffeeObj.waiterRating;
cell.ambienceRatingLabel.text=coffeeObj.ambienceRating;
cell.overallRatingLabel.text=coffeeObj.overallRating;
cell.commentsLabel.text=coffeeObj.comments;
cell.emailAddressLabel.text=coffeeObj.emailAddress;
cell.addtoMailingListLabel.text=coffeeObj.addtoMailingList;
NSString*test=coffeeObj.comments;
add your complete array data in NSMutableString and then store in text file.
// Here you set your 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:#"file.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 if it is
if(textFromFile){
NSLog(#"appending");
NSString *textToFile = [textFromFile stringByAppendingString:[NSString stringWithFormat:#" %#",yourAppendingText]];
// Here you save the updated text to that file
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
else{
NSLog(#"not appending");
[yourAppendingText writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

Read and write file in iPhone

How to make file read/write operation on iPhone?which is the path i need to specify to save the file? how can i get the current working directory in iPhone?
Thank You
Write to a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *myFile = [documentsDirectory stringByAppendingPathComponent:#"myFile"];
[data writeToFile:myFile atomically:YES];
Read a file:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"txt"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
// do something useful
}

iphone, write csv file in sandbox

i must write (at start of app) and delete is content (at the end of app) a csv in my sandbox file with a stream of data.
For your experience, what's the best way to do this?
edit:
i'm trying with this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename =#"test.csv";
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:filename];
if(![[NSFileManager defaultManager] fileExistsAtPath: fullPathToFile]) {
[[NSFileManager defaultManager] createFileAtPath: fullPathToFile contents:nil attributes:nil];
}
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath: fullPathToFile];
NSString *data = [NSString stringWithFormat:#"%#,%#\n", latitudine.text, longitudine.text];
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
it work but.... every time writedata is call i got only one row, no append. i want to collect all values of my two textlabel.
Where my mistake?
edit2:
yessss, find the solution with this code:
first i've create this one:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"myfile.csv"];
}
and in my viewDidLoad i check and if does not exist, create my file
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
NSLog(#"Route creato");
}
and in one of my method i add the code for retrieve data and append to my file:
NSString *data = [NSString stringWithFormat:#"%#,%# ", latitudine.text, longitudine.text];
//create my data to append
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ];
//say to handle where's the file fo write
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
//position handle cursor to the end of file
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
//write data to with the right encoding
Hope this helps!
If you put it in NSTemporaryDirectory(), I think it's supposed to be cleaned up on app exit — it's probably worth checking if this is the case.

document directory problem?

When i write Data(53MB ) to Document directory ,the data is not written when i check directly through application support path.i coded like this,
- (BOOL)writeApplicationData:(NSData *)data toFile:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
return NO;
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
return ([data writeToFile:appFile atomically:YES]);
}
it works fine, but when i read the data using follwing code, the data is null, anyhelp pls?
- (NSData *)applicationDataFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
return myData;
}
The code is working for me (on a small download).
Some thoughts, are you downloading the 53MB over the network? Perhaps you're trying to read it before it's finished? The "atomically" flag on write to file says:
If YES, the data is written to a backup file, and then—assuming no errors occur—the backup file is renamed to the name specified by path; otherwise, the data is written directly to path.
If you're downloading this Asynchronously and can't use partial results, you may have to wait for it to complete. Otherwise you can set the atomically:NO and read in the partial result.