简体   繁体   English

如何使用fprintf将数据写入文件

[英]How to use fprintf for writing data to a file

I want to write data from a C program to a file, so that Excel can read the file to plot a graph of the data. 我想将数据从C程序写入文件,以便Excel可以读取文件以绘制数据图。 But I'm not sure of the exact syntax to use for fprintf. 但是我不确定用于fprintf的确切语法。 I have stdlib.h declared in the very top of my program. 我在程序的顶部声明了stdlib.h。 I declared "File *fp;" 我宣布“文件* fp;” in main but I'm getting that File and fp are undeclared. 在主要,但我得到File和fp都未声明。 What could be the problem? 可能是什么问题呢?

**EDIT: My program compiles and runs but now my output file doesn't contain any data This is what I have at the end of a while loop that does some computations.. **编辑:我的程序可以编译并运行,但是现在我的输出文件不包含任何数据。这是我在进行一些计算的while循环结束时所拥有的。

 fp = fopen( "out_file.txt", "w" ); // Open file for writing

 fprintf(fp, "x = %f, y = %f, vx = %f, vy = %f, time = %f, ", x,y,vx,vy,time);

Your logic should look something like this: 您的逻辑应如下所示:

fp = fopen( "out_file.txt", "w" ); // Open file for writing

while ( some condition )
{

    ... some calculations

    fprintf(fp, "x = %f, y = %f, vx = %f, vy = %f, time = %f, ", x,y,vx,vy,time);
}

fclose(fp);

stdio文件类型为FILE (全部大写)。

#include <stdio.h>

should be enough, but be careful because the structure's name is FILE (all uppercase) and not File. 应该足够,但是要小心,因为结构的名称是FILE(全部大写)而不是File。 Finally, dont forget to close the file calling fclose() 最后,不要忘记关闭调用fclose()的文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM