简体   繁体   English

如何使用 NSFileHandle 打开文本文件

[英]how to open text file with NSFileHandle

I am trying to open a small text file to test some NSFileHandle functions on the file.我正在尝试打开一个小文本文件来测试文件上的一些 NSFileHandle 函数。 however I cannot figure out how to do this, if you could tell me what I am missing that would be great.但是我无法弄清楚如何做到这一点,如果你能告诉我我错过了什么,那就太好了。

//.h //。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

//.m //.m

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

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

 [nCode closeFile];
}

all I am doing here is trying to open the file, however each time I press the button I recive the error message "Open of nCode for reading failed"... what am I doing wrong?我在这里所做的只是试图打开文件,但是每次按下按钮时,我都会收到错误消息“打开 nCode 以读取失败”......我做错了什么?

from this I am hoping to find a way to let the user enter a number which represents a line in the text file and then return the text that is in that line.. dose anyone know a way of doing that?从这里我希望找到一种方法让用户输入一个代表文本文件中一行的数字,然后返回该行中的文本..有人知道这样做的方法吗? is it possible?可能吗?

Most likely the problem is the file path since you're not specifying a full path name.最有可能的问题是文件路径,因为您没有指定完整的路径名。 When you want to access a file inside your application bundle, use -[NSBundle pathForResource:ofType] :当您想访问应用程序包中的文件时,请使用-[NSBundle pathForResource:ofType]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM