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");
5
  • 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"];? Commented Dec 22, 2017 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. Commented Dec 22, 2017 at 10:26
  • Check the target membership: stackoverflow.com/questions/10247680/… Commented Dec 22, 2017 at 10:27
  • Y I checked in Build Phase / Copy Bundle Resources. I found the file there. Commented Dec 22, 2017 at 10:33
  • Yes it works. Thank you. My problem is misspelled in file name. Commented Dec 22, 2017 at 11:30

1 Answer 1

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.