Do not mix fgets()
with fscanf()
until you are very comfortable with these functions. They do not play well together. That \n
in the format is a white space and will match any number of consecutive white space including multiple \n
, spaces, tabs, etc.
// fscanf(fin, "%d\n", &zip);
Recommend avoiding feof()
and using the return value from fgets()
.
feof()
does not become true until a file read is attempted and fails to provide a char
. This is different than "true when none left". Example: you read the last char
of a file. feof()
is still false. Code attempts to read more (and fails). Now feof()
is true. (and remains true).
Do count the lines in a simple fashion and use symmetry. Further consider more error checking. Read the zip code line as a string and then parse it as an integer.
int countLines(FILE * fin){
int count=0;
char street[100];
char city[100];
char state[100];
char zips[100];
unsigned zip;
while (fgets(street, sizeof street, fin) != NULL) {
count++;
}
rewind(fin);
if (count%4 != 0) Handle_LineCountNotMultipleof4();
// You could return here, but let's read the file again and get the data.
// This is likely part of OP's next step.
for (int i=0; i<count; i += 4) {
if ((NULL == fgets(street, sizeof street, fin)) ||
(NULL == fgets(city, sizeof city, fin)) ||
(NULL == fgets(state, sizeof state, fin)) ||
(NULL == fgets(zips, sizeof zips, fin)) ||
(1 != sscanf(zips, "%u", &zip))) handle_error();
// Remember street, city, state, still have an ending \n
do_something(street, city, state, zip);
}
return count;
}
Alternatively, to count the lines use the following. A singular difficulty occurs in reading if you have long lines, so let's check that as we go. Take this out line length
stuff if you prefer a simple answer. You could use the Maxline+1
as you buffer size instead of a fixed 100.
size_t Maxline = 0;
size_t Curline = 0;
int ch;
while ((ch = fgetc(fin)) != EOF) {
Curline++;
if (ch == '\n') {
count++;
if (Curline > Maxline) MaxLine = Curline;
Curline = 0;
}
}
if ((Maxline + 1) > 100) TroubleAhead() ; // Trouble with future (fgets(buf, 100, fin), use bigger buffers
rewind(fin);