简体   繁体   中英

Using system calls in C writing padded hex

Hey so i'm fairly new to C itself and very new to using system calls in C but i have to use it for an assignment so i was trying to practicing reading and writing to and from a file. The read works fine but for some reason the write is doing weird things. its writing to the file some kind of padded hex representation of the number i want to write to the file. Any help would be greatly appreciated!!

buffer= 10;
if (write(file, &buffer,sizeof(int)) < sizeof(int)) {
    printf("Error in writing\n");
    exit(EXIT_FAILURE);
}

when i run this it puts that in the file but when i printout the number itself it prints the correct number

0a00 0000

sizeof(int) is 4 bytes (evidently in your environment), which is 32-bits and can be represented by 8 hexadecimal digits, which is what you're seeing in the file.

You're apparently on a Little Endian machine so the least significant byte is written first. On a big endian machine you would see 0000 000a in the file instead.

sizeof(int) is 32 bits, so 4 bytes. That means 4 sets of two hex values. Does that make sense? So it should be padding it since you are writing 4 bytes worth.

Use snprintf

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main()
{
    int file = creat("afile.txt",S_IRWXU);
    int buffer= 10;
    char sbuffer[10];
    snprintf(sbuffer,sizeof(sbuffer),"%d",buffer);
    if (write(file, &sbuffer,strlen(sbuffer)) < strlen(sbuffer)) {
        printf("Error in writing\n");
        exit(EXIT_FAILURE);
    }
    close(file);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM