我需要编写一个程序来处理来自文件或 shell(用于管道处理)的输入。处理这个问题的最有效方法是什么?我基本上需要逐行读取输入,但输入可能是来自 shell 的另一个程序的输出,或者是一个文件。
谢谢
这是来自Echo All Palindromes的 C 示例,在 C 中:
int main(int argc, char* argv[]) {
int exit_code = NO_MATCH;
if (argc == 1) // no input file; read stdin
exit_code = palindromes(stdin);
else {
// process each input file
FILE *fp = NULL;
int ret = 0;
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-") == 0)
ret = palindromes(stdin);
else if ((fp = fopen(argv[i], "r")) != NULL) {
ret = palindromes(fp);
fclose(fp);
} else {
fprintf(stderr, "%s: %s: could not open: %s\n",
argv[0], argv[i], strerror(errno));
exit_code = ERROR;
}
if (ret == ERROR) {
fprintf(stderr, "%s: %s: error: %s\n",
argv[0], argv[i], strerror(errno));
exit_code = ERROR;
} else if (ret == MATCH && exit_code != ERROR)
// return MATCH if at least one line is a MATCH, propogate error
exit_code = MATCH;
}
}
return exit_code;
}
使其适应 C++:编写palindromes
接受的函数(如上)std::istream&
;传递它std::cin
(用于标准输入,或“-”文件名)或函数中ifstream
的对象main()
。
std::getline()
与函数内的给定对象一起使用以std::istream
逐行读取输入(函数不关心输入是来自文件还是来自标准输入)。
我找不到评论链接,所以发布一个答案。正如 Eugen Constantin Dinca 所说,管道或重定向只是输出到标准输入,所以你的程序需要做的是从标准输入中读取。
我不知道你提到的“逐行阅读”是什么意思,比如ftp交互模式?如果是这样,你的程序中应该有一个循环,它每次读取一行并等待下一个输入,直到你给出终端信号。
编辑:
int c;
while(-1 != (c = getchar()))
putchar(c);
我认为它是您想要使用的命名管道。但是据我所知,其他程序必须将其输出写入命名管道(如果您有权访问该程序,您可以这样做)并且您的程序将从命名管道读取。
希望这对您有所帮助。