【发布时间】: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返回之前