[英]Not reading from stdin properly
我試圖模仿unix實用程序cat的行為,但是當我調用以下形式的命令時:
貓文件1-文件2-文件3
我的程序將正確輸出file1,然后從stdin讀取,然后按EOF,它將先打印文件2,然后打印文件3,而不是第二次從stdin讀取。
為什么會這樣呢?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ASCII_LENGTH 255
int printfile(FILE *source, int N);
int main(int argc, char *argv[])
{
int currentarg = 1; //the argument number currently being processed
FILE *input_file;
//if there are no arguments, dog reads from standard input
if(argc == 1 || currentarg == argc)
{
input_file = stdin;
printfile(input_file,0);
}
else
{
int i;
for(i = currentarg; i < argc; i++)
{
printf("%d %s\n",i,argv[i]);
//if file is a single dash, dog reads from standard input
if(strcmp(argv[i],"-") == 0)
{
input_file = stdin;
printfile(input_file,0);
fflush(stdin);
fclose(stdin);
clearerr(stdin);
}
else if ((input_file = fopen(argv[i], "r")) == NULL)
{
fprintf(stderr, "%s: %s: No such file or directory\n", argv[0], argv[i]);
return 1;
}
else
{
printfile(input_file,0);
fflush(input_file);
fclose(input_file);
clearerr(input_file);
}
}
}
return 0;
}
int printfile(FILE *source, int N)
{
//used to print characters of a file to the screen
//characters can be shifted by some number N (between 0 and 25 inclusive)
char c;
while((c = fgetc(source)) != EOF)
{
fputc((c+N)%ASCII_LENGTH,stdout);
}
printf("***** %c %d",c,c==EOF);
return 0;
}
一方面,您不能期望它在關閉后可以從stdin
讀取:
fclose(stdin);
fflush(stdin);
是未定義的行為,所有僅打開用於輸入的文件上的fflush
也是如此。 這有點像沖馬桶和期待廢出來的碗,因為fflush
只為打開輸出文件中定義! 我會建議for (int c = fgetc(stdin); c >= 0 && c != '\\n'; c = fgetc(stdin));
如果您希望舍棄行的其余部分。
此外, fgetc
返回int
是有原因的: int
內部將是一個unsigned char
值或EOF
。 c
應該是一個int,而不是char
。 EOF
不是角色! 這是一個負int
數值。 它將它與任何可能的字符區分開,因為成功調用fgetc
只會返回一個正整數,而不是負EOF
。 fputc
期望以unsigned char
值形式輸入。 char
不需要取消unsigned
。 如果您的fgetc
調用成功,並且將返回值存儲到int
,則該int
應該可以安全地傳遞給fputc
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.