kachilous
kachilous

Reputation: 2529

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. 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?

**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..

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

Upvotes: 1

Views: 60631

Answers (3)

BlackBear
BlackBear

Reputation: 22979

#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()

Upvotes: 1

Ryan
Ryan

Reputation: 28177

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

Upvotes: 8

andrewdski
andrewdski

Reputation: 5505

The stdio file type is FILE (all uppercase).

Upvotes: 2

Related Questions