Re: Which programming method is better?
- From: Micah Cowan <micah@xxxxxxxxxx>
- Date: Thu, 28 Feb 2008 06:00:47 GMT
Amandil wrote:
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.
I don't consider two calls to the same function, with different
arguments, to be particularly redundant.
Evaluating the same test twice for all but the first iteration of the
loop seems a little clunky to me, though. But I agree with Ian that your
primary concern should be legibility. They seem about equivalent on that
scale, though.
BTW, note that argv[0], if not NULL, will indicate the name your program
was invoked with, and not a filename argument. So you'd want to
preincrement argv first. Also, it makes a little more sense to me, when
you're iterating over the args list with argv as opposed to an integer
index, to use *argv instead of argv[0]. But that's just a preference.
I'd also go with const char* instead of char*, since you don't plan on
changing the contents of the strings (and, in fact, should not, in the
case of the string literal).
--
Micah J. Cowan
Programmer, musician, typesetting enthusiast, gamer...
http://micah.cowan.name/
.
- References:
- Which programming method is better?
- From: Amandil
- Which programming method is better?
- Prev by Date: Re: Which programming method is better?
- Next by Date: Re: Which programming method is better?
- Previous by thread: Re: Which programming method is better?
- Next by thread: Re: Which programming method is better?
- Index(es):
Relevant Pages
|