c - 正在读取带有奇怪字符的输入文件

标签 c

我这里有这个函数,它读取以下格式的文件:

(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/

相关文章:

c - #define 和声明有什么区别

c - 在普通 C 中测量字符串大小

c - 从 C-DLL 函数读取 MATLAB 中的 int 和字符串数组

c - 为什么要在堆上而不是栈上分配内存?

剔除适用于从 View 投影矩阵中提取平面,但不适用于投影矩阵

c - ICMP主机不可达

c - 字符串在 C 中无法正确打印

c - 协议(protocol)不支持地址族 UDP C 错误发送

c - 位掩码困惑

c - C 中线程的函数签名