嗨,我有这个程序,它从带有格式的字符的文件中读取
#00
000
000
但是当我用 fgetc 读取行直到换行时,但是当我打印出字符数时,它们算作 4,但应该是 3(0-3)。为什么会这样?
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
//int row, col; BEFORE.
int row=0, col=0; //UPDATE
/* check controls that read columns are the same size */
int check=0, i;
FILE * file;
char c;
char **matrix;
matrix = malloc(sizeof *matrix * 4);
for (i = 0; i < 4; i++)
matrix[i] = malloc(sizeof *matrix[i] * 4);
file=fopen("map.map", "r");
while ((c = fgetc(file)) != EOF)
{
matrix[row][col]=c;
if (matrix[row][col]=='\n')
{
if(row==0)
check=col;
printf("%d\n", check);
row++;
if(check!=col)
return -1;
check=col;
col=0;
}
else
col++;
}
fclose(file);
printf("%d \n", check);
return 0;
}
更新
我已经调试了程序,发现使用字符读取文件的 fgetc
#00
000
000
是在开始读取 '\0' 然后开始读取 '#00...' 所以要解决这个问题,必须从缓冲区中删除这个字符。然后就像评论的那样,col 的结尾是“/r”,后来是“/n”(在系统中:Mac OS X Lion 10.7.4),所以必须牢记这一点。
新版本
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int row=0, col=0;
/* check controls that read columns are the same size */
int linelen=0, i;
FILE * file;
char c;
char matrix[3][3];
file=fopen("map.map", "r");
/* have to read the first char because its a '\0' in the beginning */
c=fgetc(file);
if(c!=EOF)
{
while ((c=fgetc(file)) != EOF)
{
/* to jump over '\r' thats from old systems */
if(c!='\r' || c!='\n')
{
matrix[row][col]=c;
col++;
}
if(c=='\n')
{
/* first time definition of line length */
if(row==0)
linelen=col;
printf("%d\n", linelen);
row++;
if(linelen!=col)
return -1;
col=0;
}
}
}
else
printf("El archivo esta vacio\n");
fclose(file);
printf("%d\n", linelen);
printf("%d, %d\n", row, col);
return 0;
}
当我调试这个程序时,它说我正在访问坏内存。
错误报告:
.....
.....
Breakpoint 1, main () at mapaprearmado.c:25
25 while ((c=fgetc(file)) != EOF)
(gdb) print c
$25 = 13 '\r'
(gdb) print row
$26 = 1
(gdb) print col
$27 = 4
(gdb) step
.....
.....
(gdb) step
Cannot access memory at address 0x0
0x0000000100000714 in start ()
我没有得到什么...