Question

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.

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top