xcode 'fopen' 返回 NULL - “没有这样的文件或目录”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18926409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 03:51:11  来源:igfitidea点击:

'fopen' returns NULL - "no such file or directory"

cxcodeterminalfopen

提问by architectpianist

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 Xcodeon 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 fopenworks. When I put in a path name, is it relative to the working directory? Will it work if I use the absolute path?

我写了一个超级简单的 C 命令行工具,它应该从argv[1]. 我正在OS X 上使用Xcode进行调试,因此运行时的工作目录是一个 Xcode 创建的目录,与我要读取的文件分开。(Xcode 自动插入参数,所以这不是问题。)我怀疑问题与我不了解如何fopen工作有关。当我输入路径名时,它是否相对于工作目录?如果我使用绝对路径它会起作用吗?

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 mainfunction:

这是我正在使用的代码 - 它在main函数中:

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.

将 arg1 更改为使用正斜杠后,它并没有改变错误。诚然,这离实际问题更近了一步。

采纳答案by Femaref

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

你的路径是错误的;您正在使用 Windows 路径。

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

将您提供的路径与 arg0 进行比较,指定可执行文件的路径。arg1必须是相同的风格。

回答by Farouq Jouti

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.txtwhich is a Windows path and you're on OS X.

是的,绝对路径适用于fopen,但这不是您的问题。我认为您的问题来自 的内容arg[1],我认为它包含C:\Users\home\Documents\test\testdoc.txt哪个是 Windows 路径并且您使用的是 OS X。