我正在尝试用 C 语言编写一个程序,该程序将从终端运行,并将接受文件中的某些行作为输入,例如“error.log”。我怎样才能做到这一点?
命令示例:./prog < error.log
If you are using the shell syntax for input redirection — that is < filename
— then you don't actually have to do anything special. You just read from stdin (e.g. plain gets
or scanf
instead of fgets
or fscanf
).
If you want to take the names of files as arguments, then, as the commenters have indicated, you can find those arguments in the argv
array passed to your main()
function, starting at index 1
.
这是开始的例子。
#include <stdio.h>
#define BLOCK_SIZE 256
int main(int argc, char** argv)
{
char buf[BLOCK_SIZE];
size_t bytes;
while(!feof(stdin)) {
bytes = fread(buf, 1, BLOCK_SIZE, stdin);
fwrite(buf, 1, bytes, stdout);
}
return 0;
}
它只是打印出您指定为的文件./prog < filetoprint.txt