C - 如果(找不到文件){使用标准输入}

Bar*_*ers 3 c stdin file input

我有一个程序从文件中读取,但如果在arguments数组中没有声明文件,那么我想从终端中的stdin读取,例如:

 ./program.out test.txt
Run Code Online (Sandbox Code Playgroud)

从test.txt读取

 ./program.out
Run Code Online (Sandbox Code Playgroud)

从stdin读取:

这是我的一些上下文代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 9

改变这些行:

fr = fopen(argv[1], "r");
if(fr==NULL){
    //fr="/dev/stdin"; <-- Piece of code I need for this stackoverflow question
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)