如何使用NSFileHandle打开文本文件

时间:2011-06-14 22:36:43

标签: iphone ios nsfilehandle

我正在尝试打开一个小文本文件来测试文件上的一些NSFileHandle函数。但是我无法弄清楚如何做到这一点,如果你能告诉我我错过了什么会很棒。

//的.h

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
    NSFileHandle *nCode;
}
@property (nonatomic, retain) IBOutlet NSFileHandle *nCode;

- (IBAction)showInfo:(id)sender;

//check for code
- (void)fetchCode:(id)sender; //this function is attached to a button in the .nib

@end

//。米

- (void)fetchCode:(id)sender{
nCode = [NSFileHandle fileHandleForReadingAtPath:@"nCode01.txt"];

if (nCode == nil) {
    NSLog (@"Open of nCode for reading failed\n");
    return;
}

 [nCode closeFile];
}

我在这里所做的就是尝试打开文件,但每次按下按钮我都会收到错误消息“打开nCode进行读取失败”......我做错了什么?

从此我希望找到一种方法让用户输入一个代表文本文件中一行的数字,然后返回该行中的文本..剂量任何人都知道这样做的方法吗?有可能吗?

1 个答案:

答案 0 :(得分:3)

问题很可能是文件路径,因为您没有指定完整路径名。如果要访问应用程序包中的文件,请使用-[NSBundle pathForResource:ofType]

NSString *path = [[NSBundle mainBundle] pathForResource:@"nCode01"
                                                 ofType:@"txt"];
nCode = [NSFileHandle fileHandleForReadingAtPath:path];