我为一个项目编写了一个文件解析器,用于解析命令行中提供的文件。
但是,我也想允许用户输入输入[,但是仅通过命令行重定向。
使用基于Linux的命令提示符,以下命令应该产生相同的结果
:./check infile.txt
(通过命令行输入文件名)./check < infile.txt
cat infile.txt | ./check
Edit
我们假设您有一个解析器,该解析器接受单个FILE*
参数并解析该文件。 (如果您编写了一个使用const char*
文件名的解析函数,那么这是通过解释为什么这样做是一个坏主意。函数应该只做一件事,而“打开文件然后解析它”则是两件事。一旦编写了一个函数,该函数执行两项无关的操作,就会立即遇到您只想执行其中一项的情况(例如仅解析流而不打开文件。)
因此使我们拥有:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myparser.h"
/* Assume that myparser.h includes
* int parseFile(FILE* input);
* which returns non-zero on failure.
*/
int main(int argc, char* argv[]) {
FILE* input = stdin; /* If nothing changes, this is what we parse */
if (argc > 1) {
if (argc > 2) {
/* Too many arguments */
fprintf(stderr, "Usage: %s [FILE]\n", argv[0]);
exit(1);
}
/* The convention is that using `-` as a filename is the same as
* specifying stdin. Just in case it matters, follow the convention.
*/
if (strcmp(argv[1], "-") != 0) {
/* It's not -. Try to open the named file. */
input = fopen(argv[1], "r");
if (input == NULL) {
fprintf(stderr, "Could not open '%s': %s\n", argv[1], strerror(errno));
exit(1);
}
}
}
return parse(input);
}
将以上大部分内容打包成一个接受文件名并返回打开的FILE*
的函数可能会更好。
答案:
您可以从stdin中输入fgets
,然后要检查文件末尾,仍然可以使用以下命令将feof
用于stdin:
while(!feof(stdin))