0

I'm making a program that read CSV files based on the arguments of the C program called read-log

example

$ ./read-log file1.csv

$ ./read-log file1.csv file2.csv nofile.csv

But I also need my program to read files when using the unix command cat but when I input:

$ cat file1.csv |./read-log

The program doesn't get any argument.

lurker
  • 56,987
  • 9
  • 69
  • 103
Ivan
  • 3
  • 1
  • 3

1 Answers1

3

Just use the FILE *stdin that is open by default:

FILE *fp;

if (argc > 1) {
    if (strcmp(argv[1], "-") == 0)     // Many utilities accept "-" for the
        fp = stdin;                    // filename to indicate stdin
    else
        fp = fopen(argv[1], "r");
}
else {
    fp = stdin;
}

When you're done using the file, make sure you only close it if you actually opened it: (Closing stdin can lead to some interesting bugs down the road!)

if (fp != stdin)
    fclose(fp);
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • 1
    +1 but you may want to add at the end: `if (fp != stdin) fclose(fp);`, just for tidiness. – paxdiablo Mar 26 '14 at 02:54
  • @paxdiablo Thanks, forgot about that. Probably did the same in the last thing I wrote that used this too :-P – Jonathon Reinhart Mar 26 '14 at 02:55
  • In a POSIX compliant environment (*e.g.*, Linux, Windows), there's no harm in `fclose(stdin);` as long as there are no more attempts to read from `stdin` after the `fclose` in the program. – lurker Mar 26 '14 at 11:19
  • Thank you Jonathon, the problem now is that if I don't use the cat command it keeps waiting for an input, and i want it to show a default file I was trying something like fp=stdin; if(fp == NULL) { filename = strdup("something.csv"); But as I said the program keeps on waiting for an input – Ivan Mar 26 '14 at 12:05
  • @user3460464 You're saying, with my code (or equivalent), and you just run `read-log` (with no inputs), the program just waits for input? That's exactly what should happen. Try running `cat` by itself. – Jonathon Reinhart Mar 26 '14 at 23:10