Home > Tips > リダイレクト/パイプでstdinを使用した後、fgets()で文字の入力を行う方法
a.exe < fileの様に、リダイレクトやパイプを使用した後、fgets()などで文字の入力を求めようとしても、
dir /b | b.exe
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include<stdio.h> #include<string.h> #include<unistd.h> int main(){ if (!isatty(fileno(stdin))){ char line[128]={0}; while ( fgets (line, sizeof (line),stdin)!=NULL){ if ( char * p= strchr (line, '\n' ))*p= '\0' ; printf ( "%s\n" ,line); } printf ( "↑から好きな数字を選んで下さい。\n" ); char number[128]={0}; fgets (number, sizeof (number),stdin); if ( char * p= strchr (number, '\n' ))*p= '\0' ; printf ( "なんでや!%s関係ないやろ!\n" ,number); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include<stdio.h> #include<string.h> #include<unistd.h> int main(){ if (!isatty(fileno(stdin))){ char line[128]={0}; while ( fgets (line, sizeof (line),stdin)!=NULL){ if ( char * p= strchr (line, '\n' ))*p= '\0' ; else while ( getchar ()!= '\n' ); printf ( "%s\n" ,line); } freopen ( "CON" , "r" ,stdin); printf ( "↑から好きな数字を選んで下さい。\n" ); char number[128]={0}; fgets (number, sizeof (number),stdin); if ( char * p= strchr (number, '\n' ))*p= '\0' ; else while ( getchar ()!= '\n' ); printf ( "なんでや!%s関係ないやろ!\n" ,number); } } |