문제

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.

도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top