How do I read a text file in Objective-c?
Can someone provide a simplest-case example of read开发者_运维技巧ing a text file?
In Objective-C you can do something like
NSString* s = [[NSString alloc] initWithContentsOfFile:@"yourfile.txt"
encoding:NSUTF8StringEncoding error:NULL];
If you really want plain C (and not objective-C), then:
#include <stdio.h>
#define BUFSIZE 100
int main(int argc, char *argv[]) {
char buf[BUFSIZE];
FILE *fp = fopen("filename.txt", "r");
if (fp == NULL) {
fprintf(stderr, "File not found\n");
return 1;
}
while(fgets(buf, BUFSIZE, stdin) != NULL) {
printf("%s", buf);
}
fclose(fp);
return 0;
}
精彩评论