C 为什么我们需要stdin作为输入函数的文件版本?
在C语言中,stdin是一个有效的文件指针,因此如果我们愿意或需要,我们可以在输入函数的文件版本中使用stdin和其他两个 为什么我们需要这样做,而不仅仅是从壳牌公司引进?有人能举一些例子吗?这里有一个例子:C 为什么我们需要stdin作为输入函数的文件版本?,c,C,在C语言中,stdin是一个有效的文件指针,因此如果我们愿意或需要,我们可以在输入函数的文件版本中使用stdin和其他两个 为什么我们需要这样做,而不仅仅是从壳牌公司引进?有人能举一些例子吗?这里有一个例子: FILE * input = argc == 2 ? fopen(argv[1], "r") : stdin; fgets(buf, sizeof buf, input); 现在,您可以将工具用作magic data.txt和magic
FILE * input = argc == 2 ? fopen(argv[1], "r") : stdin;
fgets(buf, sizeof buf, input);
现在,您可以将工具用作magic data.txt和magicFILE * input = argc == 2 ? fopen(argv[1], "r") : stdin;
fgets(buf, sizeof buf, input);
现在,如果您编写的函数适用于任何文件*,并且在更高级别上决定要将输出转到stdout,则可以将您的工具用作magic data.txt和magic
int count_chars(FILE *in);
int main(int argc, char *argv) {
if (argc == 2) { // if there is a command line argument
FILE *input = fopen(argv[1], "r"); // open that file
count_chars(input); // count from that file
} else {
count_chars(stdin); // if not, count from stdin
}
return 0;
}
此外,如果要打印错误,将使用fprintfstderr,则会发生错误\n 如果您编写的函数适用于任何文件*,并且在更高级别上,您决定将输出转到标准输出。或者从任何文件中读取*而您决定从stdin中读取 例如,如果您在wc程序中对文件中的字符进行计数,您将看到它可以从stdin或作为命令行参数给定的文件名中读取。主要可以通过检查用户是否使用$wc file.txt提供文件名或仅使用wc调用文件名,或使用其他$ls-l|wc的管道输入来做出此决定 你可以想象一个简单的主线,上面写着:
int count_chars(FILE *in);
int main(int argc, char *argv) {
if (argc == 2) { // if there is a command line argument
FILE *input = fopen(argv[1], "r"); // open that file
count_chars(input); // count from that file
} else {
count_chars(stdin); // if not, count from stdin
}
return 0;
}
此外,如果要打印错误,将使用fprintfstderr,则会发生错误\n 很少有一次我理解了答案却不理解这个问题:@zubergu:我想OP是在问为什么stdin被定义和存在。在她看来,想要阅读标准输入的人应该使用scanf,而不是fscanfstdin,….我很少理解答案但不理解这个问题:@zubergu:我想OP是在问为什么定义和存在stdin。在她看来,想要读取标准输入的人应该使用scanf,而不是fscanfstdin。。。。