Why does my file write/read not work?
I've written the following code and single stepped through it with the debugger. By the time I get to the end, readData and readString are zero length, when I expect them to be "heading\r\ndata line 1\r\ndata line 2\r\n".
Can someone please suggest why the code doesn't work? Note that I plan on holding the file open and writing more later.
Also, do I need the synchronizeFile prior to the closeFile?
And finally, any recommendation on how to [or a utility app that can] look into this applications Documents folder to see the file I'm writing? I'll also want to transfer the file to a desktop (Windows PC).
Thanks,
Helmut
CODE:
// Hgf Create record file in <Application_Home>/Documents/ folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDire ctory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (documentsDirectory) {
NSString* myRecordPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.csv", @"Recorded Date"] ];
[myRecordPath retain];
//// Create recordfile
//NSFileManager *fileManger = [NSFileManager defaultManager];
//NSString* heading = @"heading";
//NSData* fileData = [heading dataUsingEncoding: NSASCIIStringEncoding];
//if ( ![fileManger createFileAtPath:myRecordPath contents:fileData attributes: nil] ) {
// NSLog (@"Error creating recording file!\n");
//}
NSString *recordFilePath = [documentsDirectory stringByAppendingPathComponent:myRecordPath];
NSFileHandle* recordFileHandle = [NSFileHandle fileHandleForWritingAtPath:recordFilePath];
NSString* heading = @"heading\r\n";
NSData* fileData = [heading dataUsingEncoding: NSASCIIStringEncoding];
[recordFileHandle writeData:fileData];
heading = @"data line 1\r\n";
fileData = [heading dataUsingEncoding: NSASCIIStringEncoding];
[recordFileHandle writeData:fileData];
heading = @"data line 2\r\n";
fileData = [heading dataUsingEncoding: NSASCIIStringEncoding];
[recordFileHandle writeData:fileData];
[recordFileHandle synchronizeFile];
[recordFileHandle closeFile];
//NSData* readData = [recordFileHandle readDataToEndOfFile];
NSData *readData = [[[NSData alloc] initWithContentsOfFile:recordFilePath] autorelease];
NSString* readString = [[NSString alloc] initWithData:readData encoding:NSASCIIStringEncoding];
[self broadcastChatMessage:readString fromUser:/*HgF*/@"recorder"];
} else {
NSLog (@"Documents folder not found!\n");
}
|