Search code examples
objective-cfgets

Open file and read from file 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);

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

any idea why?

complete code:

#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;

}

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


Solution

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

    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
    }
    

    or use NSString:

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

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

    How to read data from NSFileHandle line by line?

    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)