How can I write int, float or other types to a file using the write system call of UNIX?
I want to do so without using any lib function like fprintf
or fwrite
.
I want to use file descriptor and not the FILE*
.
After opening again, the file must be read exactly as written, without needing to know what size to read.
As ascertained in comments, the problem is more to convert a number to a decimal numeral than to use the
write
call.To write an int or float that is readable by humans, you must convert it to a numeral, then write the characters of that numeral. For float, if the internal representation uses a different base (e.g., binary) than the numeral (e.g., decimal), then this requires a lot of work to do correctly. I would recommend either using existing open-source code or a scientific paper on the topic.
The code to convert an
int
to a decimal numeral is fairly straightforward:This is as simple as it can get (note that
stdio.h
is only included forprintf
; the read/write works without it):