Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - If (No File Found) { Use standard input }

Tags:

c

file

input

stdin

I have a program that reads from a file, but if there is no file declared in the arguments array, then I would like to read from stdin in the terminal eg:

 ./program.out test.txt

reads from test.txt

 ./program.out

reads from stdin:

here's my code for some context:

#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;
}
like image 809
Barney Chambers Avatar asked Dec 03 '25 17:12

Barney Chambers


1 Answers

Change these lines:

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

to

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;
}
like image 132
R Sahu Avatar answered Dec 06 '25 08:12

R Sahu