BowPark
BowPark

Reputation: 1460

Most efficient way to write a number in a file in C?

I need to keep trace of an int number greater than 255 in a file. It is greater than the largest unsigned char and so the use of the fputc seems to be not reliable (first question: is it always true?).

I could use fputs, by converting the digits in characters, so obtaining a string; but in the program i need the number as an int too!

So, the question in the title: what is so the most efficient way to write that number? Is there any way to avoid the conversion to string? Keep that the file should then be readed by another process, where char number should become an int again.

Upvotes: 0

Views: 110

Answers (1)

abligh
abligh

Reputation: 25139

Just write out the binary representation:

int fd;
...
int foo = 1234;
write (fd, &foo, sizeof(foo));

(and add error handling).

Or if you like FILE*

FILE *file;
...
int foo = 1234;
fwrite (&foo, sizeof(foo), 1, file);

(and add error handling).

Note that if your file is to be loaded on a different system, potential with different endianness, you might want to ensure the endianness of the bytes is constant (e.g. most significant byte or least significant byte first). You can use htnol, htons etc. for this if you want. If you know the architecture that is loading the file is the same as that saving it, there is no need for this.

Upvotes: 3

Related Questions