尝试使用NSFileHandle创建和写入文件……但它似乎不工作

时间:2022-06-02 00:16:44

What am I doing wrong here:

我在这里做错了什么:

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; 
self.gpsFilePath = [documentsDirectory stringByAppendingString: @"/gpsReadings.txt"];
self.gpsFile = [NSFileHandle fileHandleForWritingAtPath:self.gpsFilePath];
[self.gpsFile writeData:@"GPS Readings"];
[self.gpsFile closeFile];

2 个解决方案

#1


52  

I need to create the file first:

我需要先创建文件:

[[NSFileManager defaultManager] createFileAtPath:self.gpsFilePath contents:nil attributes:nil];

#2


0  

Here is the right way to do:

以下是正确的做法:

    NSString *chemin = @"fichierlocal";
    [[NSFileManager defaultManager] createFileAtPath:chemin contents:nil attributes:nil];
    NSFileHandle *handle4write = [NSFileHandle fileHandleForWritingAtPath:chemin];
    NSString *lemessage = @"Hello, World!";
    [handle4write writeData:[lemessage dataUsingEncoding:NSASCIIStringEncoding]];
    [handle4write closeFile];

#1


52  

I need to create the file first:

我需要先创建文件:

[[NSFileManager defaultManager] createFileAtPath:self.gpsFilePath contents:nil attributes:nil];

#2


0  

Here is the right way to do:

以下是正确的做法:

    NSString *chemin = @"fichierlocal";
    [[NSFileManager defaultManager] createFileAtPath:chemin contents:nil attributes:nil];
    NSFileHandle *handle4write = [NSFileHandle fileHandleForWritingAtPath:chemin];
    NSString *lemessage = @"Hello, World!";
    [handle4write writeData:[lemessage dataUsingEncoding:NSASCIIStringEncoding]];
    [handle4write closeFile];