如何让命令行参数在 C 中运行以用于输入和输出文件

Byr*_*Fry 2 c io command-line-arguments

我试图在 CMD 开发人员提示符下运行一个应用程序,它应该有一个使用命令行参数的输入文件和输出文件(我不明白,或者无法理解)。但是当我这样做时,它正在运行并结束,但没有任何内容被打印到输出文件中。

下面是我编辑了不相关代码的代码。我不知道我是不是在代码或 cmd 行开发人员提示中做错了什么。

该应用程序被调用printlines.exe,我的命令如下所示:

printlines.exe -i file.java -o output.txt
Run Code Online (Sandbox Code Playgroud)

任何建议将不胜感激。

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define LINE 1000
Run Code Online (Sandbox Code Playgroud)
void countLines(int *emptyLines, int *totalLines, int *totalComments, char *fileName, FILE *readFile)
{
    char line[LINE]; // set array to store input file data
    //set variables
    readFile = fopen(fileName, "r");
    int lines = 0;
    int comments = 0;
    int empty = 0;

    while (fgets(line, LINE, readFile) != NULL) //while loop that reads in input file line by line
    {
        /*counts lines in input file works when not using 
            command line arguments redacted to shorten */
    }

    fclose(readFile);

    *emptyLines = empty;
    *totalLines = lines;
    *totalComments = comments;
}
Run Code Online (Sandbox Code Playgroud)
int main(int argc, char *argv[])
{
    FILE *inputFile;
    FILE *outputFile;
    char *outputName;
    char *inputName;

    inputName = argv[1];
    outputName = argv[2];

    inputFile = fopen(inputName, "r");
    outputFile = fopen(outputName, "w");

    int emptyLines, totalLines, totalComments;
    countLines(&emptyLines, &totalLines, &totalComments, inputName, inputFile);
    int character;
    bool aComment = false;

    while ((character = fgetc(inputFile)) != EOF)
    {
        /* code that writes info from input to output, works 
              when not using command line arguments redacted to shorten*/
    }

    //close files
    fclose(inputFile);
    fclose(outputFile);

    printf("There are %d total lines, %d lines of code and %d comments in the file\n", totalLines, emptyLines, totalComments);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

ana*_*ciu 5

不会对命令行参数或打开文件的错误执行错误检查。我敢打赌,如果您执行以下操作,您会很快查明问题所在:

//....
if(argc < 5){ // check arguments
    fprintf(stderr, "Too few arguments");
    return EXIT_FAILURE;
}

inputFile = fopen(inputName, "r"); 
if(inputFile == NULL){ // chek if file was open
    fprintf(stderr, "Failed to open input file\n");
    return EXIT_FAILURE;
}
outputFile = fopen(outputName, "w");
if(outputFile == NULL){ // again
    fprintf(stderr, "Failed to open output file\n");
    return EXIT_FAILURE;
}
//...
Run Code Online (Sandbox Code Playgroud)

请注意,您的命令行字符串有 5 个参数,文件名位于索引 2 和 4 处,因此您需要:

inputName = argv[2];
outputName = argv[4];
Run Code Online (Sandbox Code Playgroud)

或者只是删除-iand-o因为他们似乎没有做任何事情。

我还应该注意,您可以直接在fopen函数上或函数中使用命令行参数,不需要两个额外的指针:

inputFile = fopen(argv[2], "r");
outputFile = fopen(argv[4], "w");
//...
countLines(&emptyLines, &totalLines, &totalComments, argv[2], inputFile);
Run Code Online (Sandbox Code Playgroud)