Druckermann
Druckermann

Reputation: 741

Writing a file line by line in C

I'm currently trying to get my code to write data to file exactly the way it prints it.
For some reason, when I open the textfile afterwards there is only binary data.
How do I get that to a readable format?

Code:

#include <stdio.h>

void calcData(float *x,float* y){
    float tmpX,tmpY,a,b;
    a = 2.75;
    b = 0.2;
    tmpX = *x;
    tmpY = *y;
    *x = tmpY;
    *y = (-b*tmpX) + (a*tmpY) - (tmpY*tmpY*tmpY);
    return;
}

int main(){

    FILE *datei;
    float x = 0.5;
    float y = 0.5;
    int i;
    for(i=0;i<1000;i++){
        calcData(&x,&y);
        printf("%f \t %f \n",x,y);
        datei=fopen("txt.txt","a");
        fwrite(&x,1,sizeof(float),datei);
        fwrite("\t",1,sizeof(char),datei);
        fwrite(&y,1,sizeof(float),datei);
        fwrite("\n",1,sizeof(char),datei);
        fclose(datei);

    }
}

Upvotes: 0

Views: 59

Answers (1)

bruno
bruno

Reputation: 32586

when I open the textfile afterwards there is only binary data.

because doing

   fwrite(&x,1,sizeof(float),datei);
   ..
   fwrite(&y,1,sizeof(float),datei);

you write the internal representation of the floats.

For instance the first couple of values is x=0.500000 and y=1.150000, their internal representation are 0x3f000000 and 0x3f933333 (IEEE floats are on 32b). So when you fwrite the 4 bytes of memory supporting their value depending on the endianness you write the codes 0x3f 0x0 0x0 0x0 for x and 0x3f 0x93 0x33 0x33 for y of them in the reverse order

How do I get that to a readable format?

do

fprintf(datei, "%f\t%f\n", x, y);

in the same way you did printf("%f \t %f \n",x,y);

(Note that printf("%f \t %f \n",x,y); is in fact fprintf(stdout, "%f \t %f \n",x,y); , so if this is the right way on the standard output it is also in a file)

It is also better to move datei=fopen("txt.txt","a"); before the loop and fclose(datei); after the loop

Upvotes: 6

Related Questions