【问题标题】:cannot read file in a function after writing to it in another function在另一个函数中写入该函数后无法读取文件
【发布时间】:2022-12-20 08:28:53
【问题描述】:

我想在名为func1 的函数中写入一个文件,在main 中读取此文件并将该行存储在字符串fname 中。我有类似的东西:

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


  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);
    return(0);
    } 


int main(){

        FILE *fp;
        char fname[1000]="stringInit";
        func();
        if ( ( fp= fopen("file.dat","r")) == NULL){
                printf("Couldn't open file galactic_coord.dat \n");
                exit(-1);
        }

        fgets(fname,1000,fp);
        printf(" fname = %s \n",fname);

        fclose(fp);

 return(0);

 }

我得到 fname= stringInit,我猜是因为 file.dat 没有创建,因为它仅在 main 的末尾关闭。所以我的问题是:除了在函数func 中使用字符串数组之外,还有其他解决方案吗?

【问题讨论】:

  • 这不应该编译:fprintf(fp,"%s \n",This is file.dat);
  • 关闭文件:fclose(fp); 在从func 返回之前

标签: c string file


【解决方案1】:

您需要关闭文件:

int func(){

    FILE *fp=NULL;
       if ( ( fp= fopen("file.dat","w+")) == NULL){
                printf("Couldn't open file file.dat 
");
                exit(-1);
        }
    fprintf(fp,"%s 
", "This is file.dat");
    fclose(fp);
    return(0);
} 

您还可以返回文件句柄:

FILE *func(void){

    FILE *fp=NULL;
       if ( ( fp= fopen("file.dat","w+")) == NULL){
                printf("Couldn't open file file.dat 
");
                exit(-1);
        }
    fprintf(fp,"%s 
", "This is file.dat");
    return fp;
} 


int main(void){

    FILE *fp;
    char fname[1000]="stringInit";
    fp = func();
    if (fp == NULL){
            printf("Couldn't open file galactic_coord.dat 
");
            exit(-1);
    }
    fseek(fp, 0, SEEK_SET);

    fgets(fname,1000,fp);
    printf(" fname = %s 
",fname);

    fclose(fp);

    return(0);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多