代码之家  ›  专栏  ›  技术社区  ›  Luc

从文件中读取数据

  •  1
  • Luc  · 技术社区  · 15 年前

    我需要阅读我在桌面上保存的文件中写的所有行。 文件格式为.txt;我尝试使用stringWithContentsOfFile,但程序冻结。 我尝试使用GDB,我注意到,虽然路径是正确的,但应该包含数据的字符串返回nil。

    我错过了什么重要的事情吗?

    1 回复  |  直到 11 年前
        1
  •  3
  •   coneybeare    15 年前

    NSString *string;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([paths count] != 0) {
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *newFile = [documentsDirectory stringByAppendingPathComponent:@"filename.txt"];
        NSFileManager *fm = [NSFileManager defaultManager];
        if ([fm fileExistsAtPath:newFile]) {
            string = [NSString stringWithContentsOfFile:newFile];
        }
    }
    

    如果从那里读取,则需要替换捆绑目录的documents目录。

    编辑

    我抢了枪。这似乎不是iPhone的问题。尽管如此,您仍需要传递完整路径,而不仅仅是文件名