says...
[ ... ]
Quote:
> while(!feof(fp)) {
This line is common among beginners, but it's _almost_ always a
mistake. You usually want to test for EOF using the function that
reads the data. In your case, you're reading the data with fgets,
which returns NULL to signal the end of the file or an error having
occurred. You generally restrict use of feof to sorting out why
fgets (or some other reading function) quit reading input.
Quote:
> for(t=0; t < MAXY; t++) {
> fgets(item[t], MAXX, fp);
> if(!*item[t]) break; /* quit on blank line */
> }
This has a serious problem: you're trying to do multiple calls to
fgets, but not checking for it returning NULL in any of them. If
your input isn't properly terminated, you'll end up with a problem.
And it's pretty much considered a given that you'll receive bad input
on a fairly regular basis, so you'd better deal with it at least
somewhat reasonably -- at least printing out an error message, not
just accepting it and producing garbage output.
Quote:
> for(i=0; i < t; i++) {
> for(j=0; item[i][j]; j++) printf("%c", item[i][j]);
> }
This looks to me like a long, slow way of handling the job. Worse
yet, except under a rather obscure set of circumstances, it's
probably not doing what you want.
IMO, rather than storing all the data (a waste of memory if there
ever was one) you should simply read in a line, print it out, and
then do the same for a maximum of 150 times. If you don't want to
print more than a specified width, you can limit it pretty easily
when you read the data in. One approach would look like this:
#define MAXX 80
#define MAXY 150
char buffer[MAXX+1];
// The following pair of macros turn a defined constant into a
// string. In case you care, the first one causes the macro argument
// (e.g. MAXX) to be expanded, and then passed to the second one.
// The second then turns the expanded argument (80) into a string
// ("80"). We simply embed that into the middle of the format string
// so all of them get concatenated into one long format string.
//
#define S(x) #x
#define STR(x) S(x)
for (i=0; i<MAXY; i++) {
scanf("%" STR(MAXX) "[^\n]%*[^\n]", buffer);
scanf("%*c");
puts(buffer);
Quote:
}
I've separated this into two calls to scanf instead of one because we
more or less expect the second conversion in the first call to fail
on a regular basis (when the input fits into the buffer). If a
format conversion fails, all the rest of the conversions are ignored,
and we don't want to skip reading and discarding the new-line when
all the input fits into the buffer we provided.
--
Later,
Jerry.
The universe is a figment of its own imagination.
--