0

我只是想在Objective C中写入一个.txt文件。这是代码:

BOOL success = [str writeToFile:@"tmp/cool.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];

    if(success)
    {
        NSLog(@"done writing!");
    }
    else
    {
        NSLog(@"writing failed: %@", [error localizedDescription]);
    }

此代码的输出是“文件夹cool.txt 不存在”。我不明白这一点,因为“.txt”会认为它是文件。

我究竟做错了什么?

4

2 回答 2

5

我为你写了一个演示,假设你使用 iOS。

NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"]; //get tmp path
NSString *filePath = [path stringByAppendingPathComponent:@"cool.txt"];

NSString *str = @"hello world";
NSError *error;
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

NSString *str1 = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@", str1);
于 2012-06-10T12:50:59.080 回答
0

假设您使用 iOS 作为平台...

  1. 您需要首先获取应用程序的文档目录,以便您可以写入该目录(您可以使用库或临时目录,但最常见的是文档目录)

  2. 您必须确保文档目录下存在“tmp”目录。

于 2012-06-10T12:53:13.977 回答