0
votes

The following is my code and I have the newfile2 in the same directory as main.m is located(see image) but I am getting File read failed error. Where am I going wrong?

import

int main(int argc, const char * argv[]) {

@autoreleasepool {

    NSFileManager *fm;
    NSData *fileData;

    fm = [NSFileManager defaultManager];

    //Read from the file nwefile2

    fileData = [fm contentsAtPath:@"newfile2"];

    if (fileData == nil) {
        NSLog(@"File read failed");
        return 1;
    }

    //Write the data to a file

    if ([fm createFileAtPath:@"newfile3" contents:fileData attributes:nil] == NO) {
        NSLog(@"File creation failed");
        return 2;
    }

    NSLog(@"File copy successful");
}
return 0;
}

image showing the file structure

2

2 Answers

0
votes

The problem is that this line doesn't say where to find the file:

fileData = [fm contentsAtPath:@"newfile2"];

You are assuming that a partial path will find the file (perhaps because you think the working directory is the same directory as your program?), but that is a false assumption. Nothing is known about what the working directory is! You have to be specific about where the file is.

0
votes

The correct way to specify the path in-spite of hardcoding the path is use below api of NSBundle class:-

- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension

Write like that below:-

  fileData = [fm contentsAtPath:[[NSBundle mainBundle] 
                              pathForResource:@"newfile2" ofType:@"fileExt"]];

Note:- Before fetching the file path, your file should be present in the resource directory,.