Why does this program not work as expected? (Read the file test.txt and output it to stdout as written in the file)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define GRIDWIDTH 10
#define GRIDHEIGHT 10
FILE *fin;
//#define POINTERS
#ifdef POINTERS
char *grid[GRIDHEIGHT];
#else
char grid[GRIDHEIGHT][GRIDWIDTH];
#endif
int main(int numargs, char **firstarg) {
fin = fopen("test.txt", "r");
int i, j;
int fx, fy, fd = 0;
int cx, cy, cd = 0;
for (i = 0; i < GRIDHEIGHT; ++i) {
#ifdef POINTERS
grid[i] = malloc(GRIDWIDTH);
#endif
#if 1
for (j = 0; j < GRIDWIDTH; ++j) {
grid[i][j] = getc(fin);
}
#else
if (fread(grid[i], 1, GRIDWIDTH, fin) != GRIDWIDTH) {
printf("Could not read all chars on the line\n");
system("pause");
}
#endif
fseek(fin, 1, SEEK_CUR);
}
for (i = 0; i < GRIDHEIGHT; ++i) {
#if 1
for (j = 0; j < GRIDWIDTH; ++j) {
putc(grid[i][j], stdout);
}
#else
if (fwrite(grid[i], 1, GRIDWIDTH, stdout) != GRIDWIDTH) {
printf("Could not write all chars on the line\n");
system("pause");
}
#endif
printf("\n");
}
system("pause");
}
And here's test.txt:
Code:
*...*.....
......*...
...*...*..
..........
...*.F....
*.....*...
...*......
..C......*
...*.*....
.*.*......
What happens is that it writes the first line correctly, but then the following lines all comes after one extra new line too much; instead they miss their last char. So the print to stdout looks like this:
Code:
*...*.....
......*..
...*...*.
.........
...*.F...
*.....*..
...*.....
..C......
...*.*...
.*.*.....
Why? I have tried different implementations as well, as you can see from the preprocessing code, but it doesn't matter.