从命令行读取文件,文件名作为参数

Reading a file from command line, name of the file as an argument

我应该打开并读取这个文件,当我 运行 程序时将它的名称作为命令行参数传递,但它一直在经历同样的错误,即打开失败错误 i在我的 program.The 文件中设置的是正确的文件夹,我还打印了参数,也看到包含程序名称的参数没有很好地存储,但它只是失败的 fopen 函数。任何人都可以帮忙我? 这是代码:

 int main(int argc, const char * argv[])
{
if(argc != 2)
{
    fprintf(stderr, "Error: please insert just the name of the file after the one of the program!\n");
    exit(EXIT_FAILURE);
}

FILE *foo;
foo = fopen(argv[1], "r");

if(foo == NULL)
{
    printf("Error: failed to open the file\n Argument: %s\n", argv[1]);
    exit(EXIT_FAILURE);

}

这里我留下截图

command line screenshot

how i place the txt file

its position

the program working properly if not run from the cmd line

这是你的问题:

由于您只将文件名传递给程序,它会在其当前工作目录中查找。而我们从前面命令行的ls命令中看到,当前工作目录下只有两个文件: main.c 和证明。文件 ex3.txt 不存在。

根据屏幕截图,这些命令行的当前工作目录似乎是 ~/documents/computer science xcode project/21:12/ex3/ex3, 但是 ex3.txt 文件实际上在目录中 <something obscured by pulldown>/ex3-<something>/Build/Products/Debug.

显然 IDE 使用那个 Debug 目录,而不是 ex3 目录, 作为其当前工作目录, 因为它设法在那里找到 ex3.txt 而无需您在文件名前提供任何目录路径。