Re: Which kind of loop do I use, do or while?
- From: fred.l.kleinschmidt@xxxxxxxxxx
- Date: Thu, 28 Feb 2008 07:52:58 -0800 (PST)
On Feb 27, 7:38 pm, Amandil <mazwo...@xxxxxxxxx> wrote:
Hi, I was wondering if someone could give me some advice. I'm using
C, so the constructs are those of that language, but the question is
not really language specific.
In my program, I want to process either the standard input (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 (there are arguments) {
assign filename to argument, shift args over (argv++);
open file, assign fp to FILE pointer;
Check for error while opening file
If there was an error, skip to next iteration (continue);
}
} /* 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:
int error = 0;
FILE *fp;
char *filename;
if (there are no files) {
process("standard input", stdin, flags)
} else {
while (there are files left) {
Assign filename, advance argv;
Open filename, assingn fp;
Check for error while opening file (of course);
If there are errors, skip to next iteration (continue);
process(filename, fp, flags);
}
}
I apologize if the format of the question is not proper for this
group.
-- Marty Amandil
Don't do it all in main(). Create small functions
to do the work:
if ( argc > 1 ) {
for ( i=1;i < argc; i++ ) {
HandleFileNamed( argv[i] );
}
}
else {
while ( string=GetNextNameFromStdin() ) {
HandleFileNamed( string );
}
}
--
Fred Kleinschmdit
.
- References:
- Which kind of loop do I use, do or while?
- From: Amandil
- Which kind of loop do I use, do or while?
- Prev by Date: Re: strlen(), K+1: clarification
- Next by Date: Re: strlen(), K+1: clarification
- Previous by thread: Re: Which kind of loop do I use, do or while?
- Next by thread: Requirement for a Programming Language for Games (Strategic games)
- Index(es):
Relevant Pages
|