【发布时间】:2021-03-15 07:45:13
【问题描述】:
我正在尝试在 CMD 开发人员提示符下运行一个应用程序,它应该有一个使用命令行参数的输入文件和输出文件(我不明白,或者无法理解)。但是当我这样做时,它正在运行并结束,但没有任何内容被打印到输出文件中。
以下是我的代码,其中不相关的代码已被编辑。不知道是代码有问题还是命令行开发者提示有问题。
该应用名为printlines.exe,我的命令如下所示:
printlines.exe -i file.java -o output.txt
任何建议将不胜感激。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define LINE 1000
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;
}
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;
}
【问题讨论】:
-
检查来自
fopen的返回值 -
在取消引用
argv[2]之前,您应该验证argc >= 3。 -
从您的示例中,我希望
argv[1]是字符串-i。你真的要打开一个名为-i的文件吗? -
嗯,好吧,所以我添加了错误检查,它说目录中没有这样的文件,但文件肯定在那里。
-
@WilliamPursell 我现在终于明白了。 (这可能有点讽刺,但我确实理解)
标签: c io command-line-arguments