Append data to the sandbox path instead of overwriting the previous data.
The Spring Festival is approaching. This is a busy time, and there is no time to write a blog for various projects.
/**
* @ Brief append the written data to the sandbox path
*
* @ Param string the string to be written
* @ Param fileName write data to the file name
*/
+ (Void) writefile :( NSString *) string fileName :( NSString *) fileName
{
NSLog (@ "fileName = % @", fileName );
NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * homePath = [paths objectAtIndex: 0];
NSString * filePath = [homePath stringByAppendingPathComponent: fileName];
NSFileManager * fileManager = [NSFileManagerdefaultManager];
If (! [FileManager fileExistsAtPath: filePath]) // if it does not exist
{
NSLog (@ "------- the file does not exist, write the file ----------");
NSError * error;
If ([string writeToFile: filePath atomically: YESencoding: NSUTF8StringEncodingerror: & error])
{
NSLog (@ "------ writing files ------ success ");
}
Else
{
NSLog (@ "------ Write File ------ fail, error =%@", error );
}
}
Else // append the data to the file instead of overwriting the original file.
{
NSLog (@ "------- file exists, append file ----------");
NSFileHandle * fileHandle = [NSFileHandle fileHandleForUpdatingAtPath: filePath];
[FileHandle seekToEndOfFile]; // jump the node to the end of the file
NSData * stringData = [string dataUsingEncoding: NSUTF8StringEncoding];
[FileHandle writeData: stringData]; // append the data
[FileHandle closeFile];
}
}