On most (all?) implementations, a integer stores the binary representation of a number in the bits and bytes of that integer. In the other hand, a string and something like your text file uses bytes to store the ASCII value of digits, spaces and line feeds.
int
(assuming 4 byte with 8 bit each, big endian) may store the value 1234 this way:
Address 0x42 0x43 0x44 0x45
Value 0x00 0x00 0x04 0xD2
Text NUL NUL EOT Ò
In the other hand, a string can contain the ASCII values of each character that represents a text. The String "1234" could be stored like this:
Address 0x82 0x83 0x84 0x85 0x86
Value 0x31 0x32 0x33 0x34 0x00
Text 1 2 3 4 NUL
When you do a read, you read the characters of the text file. Reading them into a char
array is easy, you do not need to do any conversation, only add the NUL-Byte at the end. When you want to get the number, you have to convert them from a string.
This means you have to read the file, you can do this with read()
if you want, and store the content in a char
array, add a NUL-Byte and then convert the resulting string with a function like strtol()
or sscanf()
.
What you are doing
What you do is reading the ASCII characters into the int
len
. When you use a debugger before the write()
call, you can check the value of len
. In my case i used this as an input file:
0
1
2
3
...
When i stop my debugger before write()
, i see that len
has the value of 170986032 == 0xA310A30
. My system is little endian, means the lowest byte is stored at the lowest address (unlike my previous example). Which means 0x30
comes first, then 0x0a
, 0x31
and 0x0A
.
From this we know that we got the following memory layout of len
.
Address Offset 0x00 0x01 0x02 0x03
Value 0x30 0x0A 0x31 0x0A
Text 0 LF 1 LF
As you can see, the text is interpreted as a int
.
How to get what you want
You want to store the data into a char
array. And then parse it. I use some pseudo code to explain it better. This is not C-Code. You should learn to write your own code. This is just to get you an idea what you have to do:
char buffer[<buffersize>] //create a buffer array
r=read(buffer) //read the file into the buffer. You may need to repeat that multiple times to get everything
if r==error //check for errors
<do some error handling here>
buffer[<one after the last read byte>]='\0' //add the NUL-Byte st the end, so that we have a string.
int values[<number of ints you want>] //create an array to store the parsed values
for(<one loop for every int>) //make the loop for every int, to parse the int
values[<index>]=strtol(buffer,&buffer,0) //parse the text to a int
if error occured:
<do some error handling here>
How to implement this in C is your task. Keep buffer sizes in mind so you do not end with UB.