2

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.

David Kaczynski
  • 1,246
  • 2
  • 20
  • 36
  • 2
    Maybe "filename" happens to start with a line that only has a number on it? – wildplasser Oct 10 '12 at 14:56
  • Are you (1) trying to read the content of the file named 'filename' using stdin or (2) trying to read the name of the file, which you would then open() and read using a file i/o? – Art Swri Oct 10 '12 at 15:01
  • @nos It was a misunderstanding on my part. I thought that `<` would read the rest of the command line as stdin, at which point I would have to open the file and read from it. However, the `<` operator opens the file and treats its contents as input into stdin. I was over-complicating the issue. – David Kaczynski Oct 10 '12 at 15:17

3 Answers3

4

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
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
3

There's no (easy) way to get the filename from a redirected stream, since all your app sees is an open file descriptor. There is a "hard" way that works only on Linux: readlink("/proc/self/fd/0").

If you must know the filename, pass it as a regular argument (./a.out filename) and look at argv[1] instead of using input redirection.

But, since you just want to read the file (and you don't care about the filename), just read from stdin as you are doing already.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
1

Looks like you are trying to pass some file name via stdin to your program. In this case filename should be a file, not a string. What you need is to simply pass the file name you need as a command argument (./a.out filename) and extract it in your program from argv.

Maksim Skurydzin
  • 10,301
  • 8
  • 40
  • 53