A
Amandil
Hi, I was wondering if someone could give me some advice. This
question is not necessarily C-specific, but it is the language I am
using, and I am unsure about one point in C.
In my program, I want to process either the stdin or the list of files
on the command line. I have two ways of doing this, and I'm asking if
there is any advantage to doing it one way or the other.
Method 1: (using C pseudo-code)
FILE *fp = stdin;
char *filename = "standard input";
do {
if (argv[0] != NULL) {
filename = *argv++;
fp = fopen(filename, "r");
if (!fp) {
perror(filename);
continue; /* Will this jump to test at bottom? */
}
} /* Otherwise there are no files: Assemble stdin (default) */
process(filename, fp, flags);
} while (argv[0] != NULL);
The alternative method would be not to enter the loop if there are no
files:
Method 2:
FILE *fp;
char *filename;
if (argv[0] == NULL) {
process("standard input", stdin, flags)
} else {
while (argv[0]) {
filename = *argv++;
fp = fopen(filename, "r");
if (!fp) {
perror(filename);
continue;
}
process(filename, fp, flags);
}
}
I hope my question is not considered OT. It's really a question of
code redundancy or speed. Note that the usual method of calling the
program is with filenames.
-- Marty Amandil
question is not necessarily C-specific, but it is the language I am
using, and I am unsure about one point in C.
In my program, I want to process either the stdin or the list of files
on the command line. I have two ways of doing this, and I'm asking if
there is any advantage to doing it one way or the other.
Method 1: (using C pseudo-code)
FILE *fp = stdin;
char *filename = "standard input";
do {
if (argv[0] != NULL) {
filename = *argv++;
fp = fopen(filename, "r");
if (!fp) {
perror(filename);
continue; /* Will this jump to test at bottom? */
}
} /* Otherwise there are no files: Assemble stdin (default) */
process(filename, fp, flags);
} while (argv[0] != NULL);
The alternative method would be not to enter the loop if there are no
files:
Method 2:
FILE *fp;
char *filename;
if (argv[0] == NULL) {
process("standard input", stdin, flags)
} else {
while (argv[0]) {
filename = *argv++;
fp = fopen(filename, "r");
if (!fp) {
perror(filename);
continue;
}
process(filename, fp, flags);
}
}
I hope my question is not considered OT. It's really a question of
code redundancy or speed. Note that the usual method of calling the
program is with filenames.
-- Marty Amandil