test1.c:
int main(int argc, char *argv[])
{
FILE* fp = fopen("test.txt","rw");
int n,m,q;
scanf(" %d%d%d",&n,&m,&q);
struct test_t test;
while (fscanf(fp,"%d%s%d%d%d%d%d%d%d%*d",&test.line,test.data,&test.number[0],&test.number[1],&test.number[2],&test.number[3],&test.number[4],&test.number[5],&test.number[6])!=EOF) {
//do something.....
}
return 0;
}
test2.c:
int main(int argc, char *argv[])
{
int n,m,q;
scanf(" %d%d%d",&n,&m,&q);
struct test_t test;
FILE* fp = fopen("test.txt","rw");
while (fscanf(fp,"%d%s%d%d%d%d%d%d%d%*d",&test.line,test.data,&test.number[0],&test.number[1],&test.number[2],&test.number[3],&test.number[4],&test.number[5],&test.number[6])!=EOF) {
//do something....
}
return 0;
}
test_t的定义:
struct test_t {
int line;
char* data;
int number[7];
};
我的测试.txt:
141 2015-12-05 19 16 35 06 34 46 09 00
124 2015-12-08 49 25 10 09 40 48 32 00
143 2015-12-10 09 29 24 47 32 34 42 00
当我使用 test1.c 时,出现段错误。但是当我使用 test2.c 时,它运行良好。只需更改 FILE* fp = fopen("test. txt","rw");
。是什么导致了这种差异。
最佳答案
您正在调用 UB,因为您从未为 char* data;
分配内存。修复:
malloc
在while
循环之前有足够的内存:test.data = malloc(32); if(!test.data) { fprintf(stderr, "malloc failed...Bailing out!\n"); exit(-1); }
使用后,
free(test.data);
使用预定义大小的数组而不是指向
char
的指针:char data[32];
此外,如@AshishAhuja said ,还要检查fopen
的返回值。
关于c - 在不同的位置打开文件会导致不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389625/