Results 1 to 3 of 3

Thread: Reading/Writing floats from/to files

  1. #1

    Thread Starter
    Member
    Join Date
    May 2002
    Location
    Great Britain
    Posts
    60

    Reading/Writing floats from/to files

    How can I read and write float values to and from a file (using fopen, fwrite etc.)

    Ideally each float value would take up 4 bytes on the file, but I'm not sure how to do this. Can anyone help?

  2. #2
    Junior Member MikeyD's Avatar
    Join Date
    Nov 2002
    Location
    Germany
    Posts
    17
    open the files in binary-mode (b-flag).
    then use fwrite to write it unformatted to Your file.

    Mikey

  3. #3
    Frenzied Member
    Join Date
    Jul 2002
    Posts
    1,370
    Code:
    #include <stdio.h>
    
    int main(){
            FILE *fp;
            float f=99;
            int i;
            fp=fopen("test.dat","wb");
            for (i=0;i<100;i++){
                f++;
                fwrite(&f,sizeof(float),1,fp);
            }
            fclose(fp);
            fp=fopen("test.dat","rb");
            while (!feof(fp)){
                if(fread(&f,sizeof(float),1,fp)>0) printf("%f\n",f);
            }
            fclose(fp);
    	return 0;
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width