嗨,我有这个程序从带有格式
的字符的文件中读取#00
000
000
但是当我用fgetc读取行直到换行时,但是当我打印出chars的数量时,它们计为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;
}
我调试了程序并发现了使用chars读取文件的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 ()
我没得到什么......
答案 0 :(得分:3)
如果这是一个Windows样式的文本文件,问题可能就像\ n
之前的\ r \ n一样简单有一个历史的东西,mac使用\ r * nix使用\ n而windows使用\ r \ n尝试尽可能交叉兼容。所以行结尾实际上是两个字符。尝试改变:
if (matrix[row][col]=='\n')
的
if ((matrix[row][col]=='\r') || (matrix[row][col]=='\n'))
这适用于所有平台 - 虽然您需要跳过换行符之后的任何\ r或\ n,并且如果您需要检测多个换行符,则需要进行一些思考......