Can getc()/putc()/fgetc()/fputc() be used to read/write chars and floats rather than ints only from binary files? If so, how?

Recommended Answers

All 3 Replies

Yes you can use it, but I won't suggest it. Its a whole lot easier to use fread() and fwrite() to read/write to/from binary files.

// fgetc example
float f = 0;
unsigned char buf[sizeof(float)];
FILE* fp = fopen("myfile.dat", "rb");
// read a float
for(i = 0; i < sizeof(float); i++)
   buf[i] = fgetc(fp);
// move the contents of buf into the float variable
f = *(float *)buf;

Here is the same thing using fread

float f;
FILE* fp = fopen("myfile.dat", "rb");
// read the float
fread((char *)&f, sizeof(float),1,fp);

fread() is a lot less typing, lot less error prone, and more straight-forward.

Yes you can use it, but I won't suggest it. Its a whole lot easier to use fread() and fwrite() to read/write to/from binary files.

// fgetc example
float f = 0;
unsigned char buf[sizeof(float)];
FILE* fp = fopen("myfile.dat", "rb");
// read a float
for(i = 0; i < sizeof(float); i++)
   buf[i] = fgetc(fp);
// move the contents of buf into the float variable
f = *(float *)buf;

Thank you very much, I didn't realize it would be that complicated to read with fgetc(). You're right, fread() is much better :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.