打开文件并从文件中读取Objective-c [英] Open file and read from file Objective-c

查看:125
本文介绍了打开文件并从文件中读取Objective-c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开一个文件,并从中读取文件..但是我遇到了一些问题.

I'm trying to open a file, and read from it.. but I'm having some issues.

FILE *libFile = fopen("/Users/pineapple/Desktop/finalproj/test242.txt","r");
char wah[200];
fgets(wah, 200, libFile);
printf("%s test\n", wah);

此打印:\ 377 \ 376N测试,而不是文件的任何内容.

this prints: \377\376N test rather than any of the contents of my file.

知道为什么吗?

完整代码:

#import <Cocoa/Cocoa.h>
#import <stdio.h>

int main(int argc, char *argv[])
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

FILE *libFile = fopen("/Users/pineapple/Desktop/finalproj/test242.txt","r");
if(libFile){
char wah[200];
fgets(wah, 200, libFile);
printf("%s test\n", wah);
    }
[pool drain];
return 0;

}

test242.txt的字符数不超过200个.

And the test242.txt doesn't contain more than 200 chars.

推荐答案

如果这是针对Objective-C的,为什么不这样做:

If this is for Objective-C, why not do something like:

使用NSFileHandle:

use NSFileHandle:

NSString * path = @"/Users/pineapple/Desktop/finalproj/test242.txt";
NSFileHandle * fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSData * buffer = nil;
while ((buffer = [fileHandle readDataOfLength:1024])) {
  //do something with the buffer
}

或使用NSString:

or use NSString:

NSString * fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

或者如果您需要逐行阅读它:

or if you need to read it line-by-line:

如何逐行从NSFileHandle中读取数据?

IMO,除非有非常非常好的理由(例如,使用O_SHLOCK或其他方式打开文件),否则无需下拉至C级fileIO函数.

IMO, there's no need to drop down to the C-level fileIO functions unless you have a very very very good reason for doing so (ie, open a file using O_SHLOCK or something)

这篇关于打开文件并从文件中读取Objective-c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆