Search code examples
cunixhttp-redirectscanffgets

Reading integers from input redirection in C


At the Unix command line, I need to use input redirection to specify the input file:

./a.out < filename

Here is my source code:

    int main(int argc, char *argv[]) {

            char fileName[30];

            fgets(fileName, sizeof fileName, stdin);

            printf("%s\n", fileName);
    }

The program prints an integer instead of the filename. I get the same results if I use scanf("%s", fileName);

My google-fu has failed me. What am I doing wrong?

Edit: It is required to use input redirection (<, specifically), so command line arguments are not an option. However, I do not need to actually know the file name, I just need to read newline-delimited integers from the file. It appears that I am asking the wrong question.


Solution

  • I just need to read newline-delimited integers from the file. It appears that I am asking the wrong question.

    The shell's input redirection operator, <, associates the named file with the standard input of your program. Your program does not need to take any special action to open the file -- it is already opened. Just read from the input as if the user were typing at the keyboard:

    /* foo.c */
    #include <stdio.h>
    int main(int ac, char **av) {
      int i;
      while(scanf("%d", &i) == 1) {
        printf("Got one!: %d\n", i);
      }
      return 0;
    }
    

    Compile your program:

    cc foo.c
    

    And run it thus:

    a.out < filename