Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use redirection in C for file input

I need to get the file from the terminal, I know the command will look like:

./a.out < fileName.txt

I'm not sure how to use fgets() in my program to use the file requested from the terminal.

like image 933
Dexter Avatar asked Oct 19 '13 15:10

Dexter


1 Answers

Using redirection sends the contents of the input file to stdin, so you need to read from stdin inside your code, so something like (error checking omitted for clarity)

#include <stdio.h>

#define BUFFERSIZE 100

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    fgets(buffer, BUFFERSIZE , stdin);
    printf("Read: %s", buffer);
    return 0;
}
like image 70
Nigel Harper Avatar answered Oct 02 '22 02:10

Nigel Harper