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

Windows下C语言读取已创建文件后printf无打印输出问题

C程序读取文件无输出问题修复方案

问题根因

你的代码存在以下几个核心错误导致无法正常输出内容:

  • 读取文件所用的strPtr是未初始化的野指针,没有预先分配内存空间,fscanf尝试向非法地址写入内容,触发未定义行为,直接导致输出异常。
  • 缺少fopen操作的成功性校验,若文件因权限、路径等问题打开失败,后续文件操作都会出错。
  • __mingw_asprintf动态分配的字符串内存没有主动释放,存在内存泄漏问题。
  • fscanf使用%[^\n]格式符时未限制读取长度,存在缓冲区溢出风险。

修正后可运行代码

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

// 公共concat函数提取,避免重复定义
char *concat(const char *str1, const char *str2)
{
    char *result;
    __mingw_asprintf(&result, "%s%s", str1, str2);
    return result;
}

void readfileforunit1(char *param1)
{
    char *exten = ".txt";
    char *theFileName = concat(param1, exten);

    // 预先分配1024字节缓冲区存储读取的内容
    char strBuf[1024] = {0};
    FILE *fptr = fopen(theFileName, "r");
    // 校验文件打开结果
    if (fptr == NULL) {
        printf("打开文件失败\n");
        free(theFileName);
        return;
    }
    // 限制读取长度避免溢出
    fscanf(fptr, "%1023[^\n]", strBuf);
    fclose(fptr);

    printf("Here is the text from the file using char* str:\n%s\n", strBuf);
    // 释放动态申请的文件名内存
    free(theFileName);
}

void structTest(char *param1, double param2)
{
    typedef struct
    {
        char *doc;
        double value;
    } Unit;

    Unit justThis = {param1, param2};

    char *exten = ".txt";
    char *theFileName = concat(justThis.doc, exten);

    FILE *outPutFile = fopen(theFileName, "w");
    if (outPutFile == NULL) {
        printf("创建文件失败\n");
        free(theFileName);
        return;
    }
    fprintf(outPutFile, "%s,%.2f", justThis.doc, justThis.value);
    fclose(outPutFile);
    free(theFileName);
}

int main(int argc, char *argv[])
{
    structTest("123456", 555.23);
    readfileforunit1("123456");
    return 0;
}

效果说明

修正后代码运行时会正常输出你预期的123456,555.23,如果需要保留更多小数位,调整fprintf的格式符%.2f的数字即可。

内容的提问来源于stack exchange,提问作者Mr.Green

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:39:00