c - 程序未使用命令行上指定的名称创建文件

标签 c command-line-arguments fopen getopt

对于这个程序,我应该将我的名字写入终端或用户给出的输出文件(case 'f')。

#include <stdio.h>

int main(int argc, char **argv)
{
    // no output file print to screen, print name to terminal
    if (argc < 2)
    {
        fprintf(stdout, "name\n");
    }
    //print name to output file given by user
    else
    {
        int option;
        int fFlag = 0;
        while ((option = getopt(argc, argv, "f:")) != -1)
        {
            //if case 'f' print to output file
            switch (option)
            {
                case 'f':
                    fFlag = 1;  // flag indicates writing name to file
                    break;
                    //case f or error
                case '?':
                    printf("error");
                    break;
            }
        }
        //write to name to output file
        if (fFlag)
        {
            FILE *file = fopen(argv[1], "w");
            fprintf(file, "name");
        }
    }
    return 0;
}

当我想将我的名字写入终端时,我的代码有效,但当我想将我的名字写入用户给定的文件时,它不起作用。代码编译并运行,但文件不存在。

命令行中的文件可能不存在。我应该在程序中创建文件吗?

我知道我做错了什么。谢谢大家!

最佳答案

除了评论者所说的,您正在使用 getopt对于你的部分解析,所以应该将它用于其余部分!

int main...
char *filename;    /**1**/
...
  case 'f': 
    fFlag = 1;
    filename = optarg;  /**2**/
....
  FILE *file = fopen(filename , "w");  /**3**/

说明:f:getopt 意味着 getopt 将尝试找到与 一起的选项f。在 getopt 循环中,case 'f',该选项被放入变量 optarg 中。至少对于 GNU getopt,这是指向 argv 的指针,因此您不必复制它。您可以将其指针值(位于上面的 *2*)存储到您为此目的创建的变量中(*1*)。然后您可以打开该特定文件,而不管它在 argv (*3*) 中的位置。请参阅 GNU getopt example 中选项 c 的处理。 .

编辑 您没有显示您正在使用的命令行,但我猜它类似于

./foo -f my-output-file.txt

— 在这种情况下 argv[1]-fargv[2] my-output-file.txt。 (argv[0] 是您的可执行文件的名称。)因此 fopen(argv[1], ...) 不是您想要的 ;)。

关于c - 程序未使用命令行上指定的名称创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39965867/

相关文章:

c++ - 使用fopen创建新文件时如何设置FILE*对象编码格式?

php - 从 CSV 文件中删除行

c - C 中哈希表链接的问题

c - 在C中对文件进行排序

c++ - 错误 : request for member ‘stor_begin’ in ‘v’ , 属于非类类型 ‘igraph_vector_t*’

go - 隐藏标志中的选项

c - Haskell Z3 api 的段错误

python - 在 python 的 max 函数中传递 1 2 23 32 4 返回 4,为什么?

java - 使用 JewelCLI 手动输出帮助消息?

c - 在C中的另一个目录中打开文件