我这里有这个函数,它读取以下格式的文件:
(badgeno)
(name)
(location) // until it hits *
(birthday)
我通过程序在txt文件中添加了一条记录: 注:我关闭程序后检查了该文件,在我再次打开程序之前它是这样写的。
5432
Janna Wind
3321 Jupiter St
44324, Fi, CA
*
1990
但是,当我打开程序并打印记录时,它显示如下:
5432
Janna Wind
!34^&32()93321 Jupiter St
44324, Fi, CA
1990
当我检查关闭程序后存储的txt文件时,它看起来像这样:
5432
Janna Wind
!34^&32()93321 Jupiter St
44324, Fi, CA
*
1990
我假设我的“while(fgets...”位置一定有问题,但我不知道为什么。奇怪的字符意味着它从我没有分配的地址读取数据,或者类似的事情吧?如果我听起来很困惑,我很抱歉。
int readfile(struct test ** start, char filename[]){
FILE *fp = NULL;
fp = fopen(filename,"r");
int badgeno;
char fullname[45];
char location[100];
int birthday;
char line[80];
int opened = 1;
if (fp == NULL){
opened = 1;
} else {
opened = 0;
while (fscanf(fp, "%d\n", &badgeno) > 0) {
fgets(fullname, 45, fp);
strncpy(location, line, sizeof(line));
while (fgets(line, 80, fp)) {
if (strcmp(line, "*\n") == 0) {
line[0] = '\0';
break;
}
strncat(location, line, 79 - strlen(location));
}
fscanf(fp, "%d[^\n]", &birthday);
addRecord(start, badgeno, fullname, location, birthday);
}
}
fclose(fp);
return opened;
}
我知道我的代码很乱,所以请原谅。但是,是的,当我再次重新打开程序时,可能是什么导致这些奇怪的字符出现。我的 fgets 行是否可能是代码中的问题?
最佳答案
这是你的问题:
strncpy(location, line, sizeof(line));
使用此行,您可以将(未初始化!)数组 line
复制到 location
中。由于 line
未初始化,其内容不确定,您将得到未定义的行为。
相反,您应该“清除”location
数组,以便稍后可以在循环中附加到它。在定义 location
数组时,这是最容易完成的:
char location[100] = { 0 };
这会将 location
的所有元素设置为零,即字符串终止符。
关于c - 正在读取带有奇怪字符的输入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968642/