c - 运行一个程序,我将文件名传递给 Main

标签 c parameter-passing command-line-arguments codeblocks

好吧,我假设这个答案就在那里,但是有很多人在发布代码。我找不到它实际实现的地方。我正在使用代码块,并将文件名传递给 main。但是当我点击运行时,没有传入文件名。在Codeblocks中如何传入文件名?我使用 cmd promt 还是什么?我想传入 input.txt 但我想不通。现在为了防止它崩溃,我只是将它默认为 input.txt。

nfile = fopen(argv[1], "r+");

    // Check for file open
    if (nfile == NULL) {
        nfile = fopen("input.txt", "r+"); 

        printf("FILE NAME: %s argv\n", argv);

        if (nfile == NULL) {
            printf("Failed to open file. Must have file name (input.txt)\n");
            return -1;
        }
    }

最佳答案

int main(int argc, char*argv[])

^ 这应该是函数头,要使用它,您必须使用命令提示符传递参数。

例如:如果您使用 gcc 来编译程序。 然后使用gcc yourprogram.c

之后使用./a.out input.txt运行代码

关于c - 运行一个程序,我将文件名传递给 Main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27112956/

相关文章:

c - 奇怪的错误似乎可以通过添加多余的代码行来解决。十五人游戏

命令行参数写入 make 文件

Python argparse : default argument stored as string, 未列出

c - 输入 Kernighan 和 Ritchie 的例子

CUDA-C导入位图图像

C结构: member order and memory allocation

php - 如何在表单提交时保留已设置的 GET 参数值?

class - Puppet:通过类传递参数

javascript - 在另一个函数内部调用带参数的函数

c - 如何知道 c 中是否传递了特定 optarg 选项