1

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);
kachilous
  • 2,499
  • 11
  • 42
  • 56

3 Answers3

8

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);
Ryan
  • 26,884
  • 9
  • 56
  • 83
  • thanks!! now this is sort of unrelated, but would I be able to simply import this in to Excel so that I could get a graph of the data? – kachilous May 20 '11 at 16:00
  • 2
    You'd have to change your file format a little bit for Excel to easily read it. Either CSV or tab delimited may be the easiest, e.g. `fprintf(fp, "%f\t%f\t%f\t%f\t%f\n", x,y,vx,vy,time);` – Ryan May 20 '11 at 16:04
  • Your welcome. If this is what you needed, please mark the question as answered. – Ryan May 20 '11 at 16:17
2

The stdio file type is FILE (all uppercase).

andrewdski
  • 5,255
  • 2
  • 20
  • 20
1
#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()

BlackBear
  • 22,411
  • 10
  • 48
  • 86
  • thanks but now the statement: fprintf("x = %f, y = %f, vx = %f, vy = %f, time = %f, ", x,y,vx,vy,time); is giving me an error "incompatible pointer type and incompatible argument" – kachilous May 20 '11 at 15:44
  • 2
    @kachilous: because prinff wants as first argument a pointer to the FILE structure: fprintf(file, "%d", 45) – BlackBear May 20 '11 at 15:45
  • @BlackBear - it compiles and runs now but my output file does not contain any data. I have a while loop that does some computations and then at the end 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); – kachilous May 20 '11 at 15:49
  • 2
    @kachilous - keep updating your question - it's too hard to read the inline source. also, do a printf exactly like your fprintf (minus the fp) so that you can tell if your loop is being reach. (BTW, You probably need to fclose or fflush your fp) – KevinDTimm May 20 '11 at 15:50
  • @kachilous have you closed the file? @KevinDTimm: ops, right :) – BlackBear May 20 '11 at 15:51