There are some issues with your code:
You don't show how array is defined, but I assume it is
array[20][100]
. Valid inices are therfore 0 to 19 and 0 to 100 respectively, the upper bound is exclusive in C. Your loops look like(i = 0; i <= 20; i++)
and include that bound and therefore might address the illegal array indices 20 and 100.A text file contains non-zero characters. Line breaks are indicated by the the new-line character with ASCII code 10, which in C can be written as
'\n'
.Strings in C are arrays of
char
that are terminated with a null character. You never terminate your strings. Nearly all standard string routines require strings to be zero-terminated and will therefore not produce the desired results when they are called with your array. (You also need to keep in mind to leave space for the terimating null character.)While
fscanf(file, "%c", &c)
can be used to read single characters, the standard character-reading functionc = getc(file)
has less overhead and is easier to understand at first glance.for
loops are usually used when the length of an array is known. You don't know how many equations you have and how long each equation is. Awhile
loop might be better.I guess the you
count
variable counts the equations. Because you increament it in the inner loop, you count the total amount of characters that are read.You read and overwrite the lines over and over again, because you check for
feof
in the outer loop: Read 20 lines; notice that the file hasn't reached its end; try to read 20 more lines into the same data, and so on. (Advice: Don't usefeof
; it usually doesn't do what you want. Instead, check the return values of the reading functions. For example,fscanf
will returnEOF
if the end of the file was found.)Minor quibble: When printing error messages, you should print them to
stderr
. Also, be sure to terminate them with a new-line character for tidy printing. t's also a good idea to include the file name in the message.
Putting all this together:
int read(const char *fn)
{
int i, j;
FILE *file = fopen(fn, "r");
if (file == NULL) {
fprintf(stderr, "Unable to open file %s.\n", fn);
return -1;
}
i = 0;
j = 0;
while (i < 20) {
int c = getc(file);
if (c == EOF) {
/* End of file: stop reading */
array[i][j] = '\0';
break;
}
if (c == '\n') {
/* New line: Begin new line and reset column counter */
array[i][j] = '\0';
j = 0;
i++;
} else {
if (j < 100 - 1) array[i][j++] = c;
}
}
fclose(file);
return i;
}
This function takes the file name as argument and returns the number of equations that were read. When the file could not be opened, it returns the special value -1. It reads into a global array with hardcoded sizes, however.