运行发现写入文件可以,但是读不出来,不知道为什么?
下列程序的功能是将main()方法中的a、b、c存入磁盘文件file1.txt,然后再从file1.txt中读出写入的数据显示在屏幕。
运行发现写入文件可以,但是读不出来,不知道为什么?谢谢。
#include <stdio.h>
#include <stdlib.h>
void fun(char *s, int a, double f)
{
/**********found**********/
FILE *fp;
char str[100], str1[100], str2[100];
int a1;
double f1;
fp = fopen("file1.txt", "w");
fprintf(fp, "%s %d %f\n", s, a, f);
fp = fopen("file1.txt", "r");
/**********found**********/
fscanf(fp,"%s%s%s", &str, &str1, &str2);
fclose(fp);
a1 = atoi(str1);
f1 = atof(str2);
printf("\nThe result :\n\n%s %d %f\n", str, a1, f1);
}
main()
{
char a[10]="Hello!";
int b=12345;
double c= 98.76;
fun(a,b,c);
}
[解决办法]
- C/C++ code
fscanf(fp,"%s%s%s", &str, &str1, &str2); 改为fscanf(fp,"%s%s%s", str, str1, str2);
[解决办法]
写入的格式与读出的格式不一致!
fprintf(fp, "%s %d %f\n", s, a, f);
%s%d%f之间是有空格的吧?
fscanf(fp,"%s%s%s", str, str1, str2);
这个却是没有的!
[解决办法]
文件写入后没有关闭,就打开读了
- C/C++ code
fp = fopen("file1.txt", "w"); fprintf(fp, "%s %d %f\n", s, a, f); fclose(fp); /* 需要先关闭才能读!! 或者以读写方式打开,这里使用rewind回到文件头 */fp = fopen("file1.txt", "r"); /**********found**********/ fscanf(fp,"%s%s%s", str, str1, str2);