【发布时间】:2019-12-05 02:29:49
【问题描述】:
我正在尝试从包含需要传递给我的程序的命令的输入文件中获取信息。当我执行 C 文件时,我使用./inventory test01/inventory01-actual.txt < test01/input01.txt > test01/actual01.txt。包含命令的文件是 input-01.txt。比如input-01.txt的内容如下:
PRINT
QUIT
如下面的代码所示,第一个 while 循环遍历文件 test01/inventory01-actual.txt 并解析输入。当我调用scanf 时,它只读取第一个命令(PRINT)然后程序终止。我知道我需要一个 while 循环来让它通过并读取输入文件中的每个命令,但我不确定如何在我的代码中引用它。
我也想过
while (______ ! EOF) {
....
}
...但我不确定要在空白处填写什么以引用 input-01.txt。我可以使用feof 之类的东西吗? (当然,我会将scanf 和 if-else 语句放在这个 while 循环中)。
FILE *src_file;
src_file = fopen(argv[1], "r");
//Initialize data for node
int id;
char name[MAX_NAME];
char summary[MAX_SUM];
int count;
char buffer[MAX_LEN_COMMAND];
//Parse file input line by line
while (fgets(buffer, sizeof(buffer), src_file) != NULL) {
if (sscanf(buffer, "%d, %[^,], %[^,], %d\n", &id, name, summary, &count) == INPUT_COUNT) {
if (count < 0) {
printf("Invalid count value.");
exit(EXIT_BAD_INPUT);
}
if (isEmpty(summary) || isEmpty(name)) {
//Skip this iteration
printf("RECORD NOT INSERTED\n");
continue;
}
printf("RECORD INSERTED: %d\n", id);
//Add each struct to the linked list
addRecord(list, id, name, summary, count);
} else {
printf("RECORD NOT INSERTED\n");
}
}
//Get user input for commands
char command[MAX_LEN_COMMAND];
//Keep re-prompting user for commands until you reach EOF
printf("====================\nCommand? ");
scanf("%s", command);
if (strcmp(command, "PRINT") == 0) {
print(list);
} else if (strcmp(command, "QUIT") == 0) {
quit(argv[1], list);
exit(EXIT_SUCCESS);
} else {
printf("Invalid command passed.\n");
exit(EXIT_BAD_INPUT);
}
我的目标是让我的程序读取 input-01.txt 文件中的每个命令,而我的程序目前只读取该文件的第一行。
【问题讨论】:
-
MAX_NAME, MAX_SUM, MAX_LEN_COMMAND的定义是什么?发布minimal reproducible example
标签: c while-loop io stream user-input