overwriter
overwriter

Reputation: 49

writing a byte with the "write" system call in C

Using the system call write, I am trying to write a number to a file. I want the file pointed by fileid to have 4 as '04'(expected outcome).

    unsigned int g =  4;

if (write(fileid, &g, (size_t) sizeof(int) ) == -1) 
{
     perror("Error"); exit(1);
}

I get the output '0000 0004' in my file. If I put one instead of sizeof(int) I get 00.

Is there a specific type that I missed ?

PS. I have to read this value form the file also, so if there isn't a type I'm not quite sure how I would go about doing that.

Upvotes: 2

Views: 3438

Answers (4)

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 6013

sizeof(int) will return 4; so actually, the code is writing four bytes.

Change the type of 'g' from

unsigned int 

to

unsigned char

... and, change

sizeof(int)

to

sizeof(unsigned char) .. or sizeof(g)

Then you should see that only one byte '04' will be written.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206717

If you want to save only one byte, it will be more appropriate to create a variable that is of size one byte and save it using write.

unsigned int g =  4;
unsinged char c = (unsigned char)g;

if (write(fileid, &c, 1 ) == -1) 
{
     perror("Error"); exit(1);
}

If you lose any data, it will be in the program and not in/out of files.

Upvotes: 0

zwol
zwol

Reputation: 140786

In this circumstance I would recommend using uint8_t, which is defined in <stdint.h>. On basically all systems you will ever encounter, this is a typedef for unsigned char, but using this name makes it clearer that the value in the variable is being treated as a number, not a character.

uint8_t g = 4;
if (write(fileid, &g, 1) != 1) {
    perror("write");
    exit(1);
}

(sizeof(char) == 1 by definition, and therefore so is sizeof(uint8_t).)

To understand why your original code did not behave as you expected, read up on endianness.

Upvotes: 0

Havenard
Havenard

Reputation: 27914

If writing 1 byte of g will print 00 or 04 will depend on the architecture. Usually, 32-bit integers will be stored in the memory using little-endian, meaning the less significant byte comes first, therefore 32-bits int 4 is stored as 04 00 00 00 and the first byte is 04.

But this is not always true. Some architectures will store using big-endian, so the byte order in memory is the same as its read in 32-bit hexadecimal 00 00 00 04.

Wikipedia Article.

Upvotes: 3

Related Questions