batuman
batuman

Reputation: 7304

Reading byte array from a file in Objective C

I try to read a file with byte data.

My file reading code is

    NSString *filepath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"PATH.dat"];    
    NSLog(@"\n\nthe string %@",filepath);
    NSData *fileData = [NSData dataWithContentsOfFile: filepath];
    char *fileBytes = (char *)[fileData bytes];
    NSUInteger length = [fileData length];
    NSLog(@"length %lu", (unsigned long)length);
    NSUInteger index;
    for (index = 0; index<length; index++)
    {
        char aByte = fileBytes[index];
        NSLog(@"byte %d", aByte);
    }

The following outputs show that file path is ok, but length is 0.

the string /var/containers/Bundle/Application/6D84F701-BC0E-43AD-8FD8-1F0083CE1F84/ProductName.app/PATH.dat
2017-12-22 17:54:18.746773+0800 ProductName[8704:2173252] length 0

What is wrong with my file reading?

EDIT:

if([[NSFileManager defaultManager] fileExistsAtPath: filepath])
        NSLog(@"fileexist");

Upvotes: 4

Views: 2587

Answers (1)

JoGoFo
JoGoFo

Reputation: 2008

Try getting the path of your file using this instead:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"FILENAME" ofType:@"dat"];

If that still doesn't work, try:

NSURL *fileUrl = [NSURL fileURLWithPath:filepath];
NSData *fileData = [NSData dataWithContentsOfURL:fileUrl];

Upvotes: 3

Related Questions