You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言读取txt文本存入结构体链表后输出异常问题求助

C语言员工链表读取问题修复方案

错误点排查

  • 读取逻辑错误:你当前使用fread()读取纯文本格式的员工数据,fread()仅适用于二进制文件的整块读取,无法正确解析空格分隔的文本字段,这是输出异常的核心原因
  • 函数声明缺失:Read_File和displayEmployees函数在main调用前没有声明,会导致编译报错/警告
  • 内存使用不规范:Read_File开头为newPtr申请的内存无实际作用,也没有释放,存在内存泄漏
  • 逻辑冗余:不需要额外的newPtr做数据中转,读取的字段可以直接写入新的链表节点

修复后完整代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct personTag {
    char name[20];
    int age;
};
struct officialTag {
    int deptID;
    char cmpName[20];
    double salary;
};
struct employeeTag {
    struct personTag personalInfo;
    struct officialTag officialInfo;
    struct employeeTag *next;
};

typedef struct employeeTag EMPLOYEETAG;
typedef EMPLOYEETAG *EMPLOYEEptr;

// 函数前置声明
EMPLOYEEptr Read_File(char fileName[]);
void displayEmployees(EMPLOYEETAG *root);

int main() {
    EMPLOYEEptr thisPtr = NULL;
    char fileName[15] = "employees.txt";
    thisPtr = Read_File(fileName);
    displayEmployees(thisPtr);
    
    return 0;
}

EMPLOYEEptr Read_File(char fileName[]) {
    EMPLOYEEptr startPtr = NULL, nextPtr = NULL;
    FILE *fp = fopen(fileName, "r");
    if (fp == NULL) {
        fprintf(stderr, "\nCouldn't Open File\n");
        exit(1);
    } else {
        fprintf(stderr, "\nFile Opened Successfully.\n\n");
    }

    EMPLOYEEptr newNode = NULL;
    // 按文本格式读取字段
    while (1) {
        newNode = (EMPLOYEETAG *)malloc(sizeof(EMPLOYEETAG));
        newNode->next = NULL;
        int res = fscanf(fp, "%s %d %d %s %lf", 
                        newNode->personalInfo.name,
                        &newNode->personalInfo.age,
                        &newNode->officialInfo.deptID,
                        newNode->officialInfo.cmpName,
                        &newNode->officialInfo.salary);
        // 读到文件末尾退出
        if (res == EOF) {
            free(newNode);
            break;
        }
        // 插入链表
        if (startPtr == NULL) {
            startPtr = nextPtr = newNode;
        } else {
            nextPtr->next = newNode;
            nextPtr = newNode;
        }
    }
    
    fclose(fp);
    return startPtr;
}

void displayEmployees(EMPLOYEETAG *root) {
    EMPLOYEEptr temp = root;
    printf("\nLinkedList: \n");
    while (temp != NULL) {
        printf("%s\t%d\t%d\t%s\t%.2lf\n",
               temp->personalInfo.name,
               temp->personalInfo.age,
               temp->officialInfo.deptID,
               temp->officialInfo.cmpName,
               temp->officialInfo.salary);
        temp = temp->next;
    }
    printf("NULL\n\n");
}

验证说明

将employees.txt和代码放在同一目录下编译运行,即可正常输出所有员工数据,无乱码或异常值。

内容的提问来源于stack exchange,提问作者iCydeRs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:36:02