繁体   English   中英

使用命令行输出到文件

[英]output to a file using command line

我正在编写一个程序,该程序应该能够接受命令行参数。 基本上,用户在调用程序时必须能够通过命令提示符指定文件名。 即程序应该能够接受一个参数,例如:doCalculation -myOutputfile.txt。 其中doCalculation是我的程序的名称,而myOutputfile是我要将结果写入的文件(即,将计算结果输出到指定的文件名)。

到目前为止,我可以通过命令提示符调用函数。 我不确定如何使程序写入指定的文件名(如果尚不存在,则创建此文件)。

我的代码如下:

int main(int argc, char *argv[])
{
    FILE* outputFile;
    char filename;

    // this is to make sure the code works
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }

    //open the specified file
    filename= argv[i];   
    outputFile = fopen("filename", "r");

    //write to file
    fclose(outputFile);
}

所以我注意到了几件事...

  1. 如果要写入文件,请在打开文件时将“ w”用于写入模式,而不是“ r”用于读取模式。
  2. 您将文件名声明为单个字符,而不是指向字符串的指针(字符*)。 使其成为指针将允许文件名的长度> 1(字符数组而不是单个字符)。
  3. 正如Ashwin Mukhija所提到的,在for循环将其设置为2之后,您正在使用i,实际上,您需要第二个(索引1)参数。
  4. 在open()函数中,文件名自变量作为文字“文件名”而不是文件名变量。

看看这段代码是否有助于解决您的问题,(我还在其中扔了一个fprintf()来向您展示如何写入文件)。 干杯!

int main(int argc, char *argv[])
{
    FILE* outputFile;
    char* filename;

    // this is to make sure the code works
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }

    //saftey check
    if(argv[1])
    {
        filename = argv[1];

        //open the specified file
        outputFile = fopen(filename, "w");

        fprintf(outputFile, "blah blah");

        //write to file
        fclose(outputFile );
    }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM