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

func函数写入文件后main函数无法读取,求非字符串数组类解决方案

问题分析与解决方案

你的代码运行后fname仍为初始值,核心原因是文件写入的缓冲区未被刷新到磁盘。C标准库的文件I/O默认使用缓冲机制,fprintf的内容会暂存在内存缓冲区,只有满足以下条件之一才会写入磁盘:

  • 缓冲区被填满
  • 调用fflush强制刷新
  • 调用fclose关闭文件
  • 程序正常退出(但你的func里未关闭文件,main重新打开时,之前的缓冲区内容还没同步到磁盘)

以下是几种除使用字符串数组外的解决方案:

解决方案1:在func中关闭文件

写完内容后调用fclose,既会强制刷新缓冲区到磁盘,也会释放文件资源,这是最规范的做法:

int func(){
    FILE *fp=NULL;
    if ( ( fp= fopen("file.dat","w+")) == NULL){
            printf("Couldn't open file file.dat \n");
            exit(-1);
    }
    fprintf(fp,"%s \n","This is file.dat");
    fclose(fp); // 关闭文件,触发缓冲区写入磁盘
    return 0;
}

解决方案2:在func中显式刷新缓冲区

如果需要保持文件打开(比如后续还要写入内容),可以用fflush手动把缓冲区内容同步到磁盘:

int func(){
    FILE *fp=NULL;
    if ( ( fp= fopen("file.dat","w+")) == NULL){
            printf("Couldn't open file file.dat \n");
            exit(-1);
    }
    fprintf(fp,"%s \n","This is file.dat");
    fflush(fp); // 强制刷新缓冲区到磁盘
    return 0;
}

解决方案3:修改文件缓冲模式

打开文件后设置行缓冲或无缓冲模式,让写入内容即时生效:

  • 行缓冲模式:遇到换行符时自动刷新缓冲区
  • 无缓冲模式:写入操作直接同步到磁盘

示例(行缓冲模式):

int func(){
    FILE *fp=NULL;
    if ( ( fp= fopen("file.dat","w+")) == NULL){
            printf("Couldn't open file file.dat \n");
            exit(-1);
    }
    setvbuf(fp, NULL, _IOLBF, 0); // 设置行缓冲模式
    fprintf(fp,"%s \n","This is file.dat"); // 换行符触发自动刷新
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:10:43