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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6074279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:42:26  来源:igfitidea点击:

How to use fprintf for writing data to a file

c

提问by kachilous

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. But I'm not sure of the exact syntax to use for fprintf. I have stdlib.h declared in the very top of my program. I declared "File *fp;" in main but I'm getting that File and fp are undeclared. What could be the problem?

我想将数据从 C 程序写入文件,以便 Excel 可以读取文件以绘制数据图。但我不确定用于 fprintf 的确切语法。我在程序的最顶部声明​​了 stdlib.h。我声明了“File *fp;” 在 main 中,但我发现 File 和 fp 未声明。可能是什么问题呢?

**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);

回答by Ryan

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);

回答by andrewdski

The stdio file type is FILE(all uppercase).

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

回答by BlackBear

#include <stdio.h>

should be enough, but be careful because the structure's name is FILE (all uppercase) and not File. Finally, dont forget to close the file calling fclose()

应该足够了,但要小心,因为结构的名称是 FILE(全部大写)而不是 File。最后,不要忘记关闭调用 fclose() 的文件