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

标签 c command-line argv argc

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

最佳答案

这是你的问题:

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,而不需要您在文件名前提供任何目录路径。

关于c - 从命令行读取文件,文件名作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47961254/

相关文章:

比较c中的两个文件

SQL*Plus 命令行参数在 Windows 中被覆盖

python - 设置 Macvim 以在 OSX 上进行 Python 开发

c++ - 为什么目标文件的 debug_str 这么大?

objective-c - 如何将 NSLog 的输出绑定(bind)(重定向?)到 IBOutlet 等?

java - 如何从命令行禁用 Maven Javadoc 插件?

python - 调用函数时更改 Python 3 sys.argv

C# 使用命令行调用应用程序

c - scanf 成一个字符串数组

c - 中缀到后缀