arrays - 文件的读写
问题描述
我是 c 的新手,我想检查一下我是否了解文件处理的功能是如何工作的,这是我的代码。我面临的问题是每个 x 中 fx 的评估成功存储在文件 pointinterpol.dat 上,但是当我想读取以将其内容存储在两个数组上并打印它们时,我得到了 x,y 数组的所有元素零。我不知道出了什么问题?
int main(void)
{
int i = 0;
float xe;
float x[8], y[8];
float fx = 1 / (1 + 25 * xe * xe);
FILE* fptr = NULL;
FILE* fread;
fptr = fopen("pointinterpol.dat", "w");
xe = -1;
while (i++ < 8)
{
fprintf(fptr, "%.3f %.3f\n", xe, 1 / (1 + 25 * xe * xe));
xe += 0.25;
}
i = 0;
fread = fopen("pointinterpol.dat", "r");
while (fscanf(fread, "%f %f", &x[i], &y[i]) == 2)
{
i++;
}
i = 0;
while (i < 8)
{
printf("\nx[%d] = %.2f *** y[%d] = %.2f\n", i, x[i], i, y[i]);
i++;
}
flcose(fptr);
fclose(fread);
return 0;
}
解决方案
正如评论中所指出的,您需要fclose()
在完成将数据写入文件后调用。我fclose()
在第一个 while 循环之后添加,我能够看到预期的输出:
#include <stdio.h>
int main(void) {
int i=0;
float xe;
float x[8],y[8];
float fx = 1 / (1 + 25*xe*xe);
FILE *fptr = NULL;
FILE *fread;
fptr = fopen("pointinterpol.dat","w"); // -> File Opened for Writing
xe = -1;
while( i++ < 8 ) {
fprintf(fptr,"%.3f %.3f\n",xe,1/(1+25*xe*xe));
xe += 0.25;
}
fclose(fptr); // -> Writing finished, close stream
i=0;
fread = fopen("pointinterpol.dat","r"); // -> File opened for reading
while(fscanf(fread,"%f %f",&x[i],&y[i]) == 2) {
i++;
}
i=0;
while( i < 8 ) {
printf("\nx[%d] = %.2f *** y[%d] = %.2f\n",i,x[i],i,y[i]);
i++;
}
fclose(fread); // -> Reading finished, close stream after use
return 0;
}
当我运行它时,我得到这个输出:
x[0] = -1.00 *** y[0] = 0.04
x[1] = -0.75 *** y[1] = 0.07
x[2] = -0.50 *** y[2] = 0.14
x[3] = -0.25 *** y[3] = 0.39
x[4] = 0.00 *** y[4] = 1.00
x[5] = 0.25 *** y[5] = 0.39
x[6] = 0.50 *** y[6] = 0.14
x[7] = 0.75 *** y[7] = 0.07
推荐阅读
- drupal - 如何在drupal 8中显示子类别的所有产品
- python-3.x - Python 3 发送带有多个数据字段的 post 请求
- c - windows网络驱动器上的文件操作错误
- regex - 在括号之间的字符串中查找特定字符的所有出现,该字符串位于另一个字符串本身之后(REGEX)
- arrays - Matlab中3D点数组的熵函数?
- javascript - SyntaxError:JSON 解析错误意外的 EOF
- nrwl-nx - 将无服务器与 nrwl nx 集成
- quantlib - 如何在 QuantLib 中使用掉期利率助手来构建具有浮动腿固定天数的收益率曲线
- sql-server - 过去一小时聚合数据的自动报告生成
- php - 将 Google Recaptcha 添加到表单时出现问题