简体   繁体   中英

'fopen' returns NULL - “no such file or directory”

I've written a super simple C command line tool that's supposed to read a file out from the path specified in argv[1] . I'm debugging using Xcode on OS X, so the working directory at the time of running is an Xcode-created directory separate from the file I want to read. (Xcode plugs in the arguments automatically, so that's not the problem.) I suspect the problem is related to my not understanding how fopen works. When I put in a path name, is it relative to the working directory? Will it work if I use the absolute path?

I've checked this post , this one , and this one , but they don't seem to help me in this case.

Here's the code I'm using - it's in the main function:

for (int i = 0; i < argc; i++)
    printf("arg%i: %s\n", i, argv[i]);

if (argc > 1)
{
    //Open the file specified by the first argument
    system("pwd");
    FILE *file = fopen(argv[1], "r");    //Always returns NULL

    if (file)
        //This isn't ever reached
    else
        printf("%s\n", strerror(errno));        
}

The output looks like this:

arg0: /Users/home/Library/Developer/Xcode/DerivedData/VSSequenceAlignment-avlfehlrtqiybygqfgueezoysnyi/Build/Products/Debug/VSSequenceAlignment
arg1: C:/Users/venkateshsivaramanDP/Documents/test/testdoc.txt
/Users/venkateshsivaramanDP/Library/Developer/Xcode/DerivedData/VSSequenceAlignment-avlfehlrtqiybygqfgueezoysnyi/Build/Products/Debug
No such file or directory

After changing the arg1 to use forward slashes it hasn't changed the error. Admittedly it's a step closer to the actual problem.

Your path is wrong; you are using a Windows path.

Compare your supplied path to arg0, specifying the path to the executable. arg1 has to be in the same style.

Yes, absolute paths work with fopen , but that's not your problem. I think that your problem comes from the content of arg[1] , and I think it contains C:\\Users\\home\\Documents\\test\\testdoc.txt which is a Windows path and you're on OS X.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM