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);