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

问题描述 投票:0回答:1

我应该打开并读取此文件,当我运行程序时,将其名称作为命令行的参数传递,但它继续经历相同的错误,即我在程序中设置的打开失败错误。文件是正确的文件夹,我也打印了参数也看到包含程序名称的那个没有很好地存储,但它是,它只是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

c command-line argv argc
1个回答
3
投票

这是你的问题:

enter image description here

由于您只将文件名传递给程序,因此它会查找当前的工作目录。正如我们在前一个命令行上的ls命令中看到的那样,当前工作目录中只有两个文件:main.c和prova。文件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而不需要在文件名前面提供任何目录路径。

© www.soinside.com 2019 - 2024. All rights reserved.