我有一个从文件中读取的程序,但是如果参数数组中没有声明文件,那么我想从终端的标准输入中读取例如:
./program.out test.txt
从 test.txt 读取
./program.out
从标准输入读取:
这是我的一些上下文代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *fr;
char *line;
char *word;
size_t len =256;
int i=0;
int sum=0;
char *vali;
const char delim = ' ';
int flag=0;
int main(int argc, char* argv[]){
line = (char *)malloc(len);
word = (char *)malloc(len);
/*
line = (char *)malloc(sizeof(&len));
word = (char *)malloc(sizeof(&len));
vali = (char *)malloc(sizeof(&len));
*/
fr = fopen(argv[1], "r");
if(fr==NULL){
//fr="/dev/stdin"; <-- Piece of code I need for this stackoverflow question
}
while (getline(&line, &len, fr) != -1){
/* printf("%s", line ); */
if(strlen(line) != 1){
sscanf(line,"%s%*[^\n]",word);
printf("%-10s ", word);
char *scores = line + strlen(word) + 1;
/* printf("scores: %s", scores); */
vali=strtok(scores, &delim);
while(vali != NULL){
sum=sum+atoi(vali);
vali = strtok(NULL, &delim);
}
printf("%3d\n", sum);
sum=0;
}
}
fclose(fr);
free(line);
// free(word);
// free(vali);
return 0;
}
最佳答案
更改这些行:
fr = fopen(argv[1], "r");
if(fr==NULL){
//fr="/dev/stdin"; <-- Piece of code I need for this stackoverflow question
}
到
if ( argc > 1 )
{
// A file was passed in as the first argument.
// Try to open it.
fr = fopen(argv[1], "r");
if(fr==NULL){
// Deal with the error of not being able to open the file.
}
}
else
{
// Nothing was passed to the program.
// use stdin.
fr = stdin;
}
关于C - If (No File Found) { 使用标准输入 },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204792/