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

C语言调用函数后无法在文本编辑器查看文件数据的问题

问题分析与解决方案

核心错误

你的代码里有个致命问题:用fopen("payment.txt", "w")打开文件时,"w"是写入模式——它会清空现有文件内容,甚至创建空文件,导致fread根本读不到任何数据。这是数据无法显示的直接原因。

另外,你希望调用函数后能在文本编辑器查看数据,需确保数据以可读的文本格式存储,而非二进制结构体数据(二进制数据在文本编辑器里会显示乱码)。


修正方案(同时输出到控制台和文本文件)

下面的代码会读取源文件数据,同时打印到控制台,并写入一个可直接用文本编辑器打开的文件:

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

// 先定义结构体(假设你已定义,这里补充完整)
struct flat {
    int no;
    char name[50];
    char surname[50];
    float payment;
    char date[20];
};

void payment_list()
{
    struct flat d;
    FILE *read_file;
    FILE *text_file;

    // 1. 以二进制只读模式打开源文件(如果源文件是文本格式,改成"r"即可)
    read_file = fopen("payment.txt", "rb");
    if (read_file == NULL)
    {
        printf("无法打开文件\n");
        return;
    }

    // 2. 创建可编辑的文本文件,用于存储可读格式的数据
    text_file = fopen("payment_report.txt", "w");
    if (text_file == NULL)
    {
        printf("无法创建报告文件\n");
        fclose(read_file);
        return;
    }

    // 3. 输出表头到控制台和文本文件
    const char *header = "\nFlate No\tName Surname\tPayment\t\tDate\n";
    const char *separator = "--------------------------------------------------------\n";
    printf("%s%s", header, separator);
    fprintf(text_file, "%s%s", header, separator);

    // 4. 读取数据并同时输出
    while (fread(&d, sizeof(struct flat), 1, read_file) == 1)
    {
        printf("%d\t\t%s %s\t\t%.2f\t\t%s\n", d.no, d.name, d.surname, d.payment, d.date);
        fprintf(text_file, "%d\t\t%s %s\t\t%.2f\t\t%s\n", d.no, d.name, d.surname, d.payment, d.date);
    }

    // 5. 关闭文件
    fclose(read_file);
    fclose(text_file);
    printf("数据已保存到payment_report.txt,可直接用文本编辑器查看\n");
}

关键修正点

  • 将文件打开模式从"w"改为"rb"(二进制只读,适配结构体的二进制存储);如果源文件本身是文本格式,改成"r"即可。
  • 新增payment_report.txt文件,用fprintf以可读文本格式写入数据,解决文本编辑器查看乱码的问题。
  • 保留控制台输出,同时满足文件查看需求。

内容的提问来源于stack exchange,提问作者Amna A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:47:32