4

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");
Zee
  • 1,865
  • 21
  • 42
batuman
  • 7,066
  • 26
  • 107
  • 229
  • Could you check before hand if `[[NSFileManager defaultManager] fileExistsAtPath: filepath]` returns true? If you added yourself the file into your bundle, what about doing: `NSString *filepath= [[NSBundle mainBundle] pathForResource:@"PATH" ofType:@"dat"];`? – Larme Dec 22 '17 at 10:09
  • @Larme I added as in EDIT. But there is no output as fileexist. That means file doesn't exist? I put file as right click to project / Add file to project option. – batuman Dec 22 '17 at 10:26
  • Check the target membership: https://stackoverflow.com/questions/10247680/adding-resource-files-to-xcode – Larme Dec 22 '17 at 10:27
  • Y I checked in Build Phase / Copy Bundle Resources. I found the file there. – batuman Dec 22 '17 at 10:33
  • Yes it works. Thank you. My problem is misspelled in file name. – batuman Dec 22 '17 at 11:30

1 Answers1

3

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];
JoGoFo
  • 1,928
  • 14
  • 31