How big is an integer?
What is the correct way to work out how many bytes an int is? and how do I write an int to a file descriptor?
Here is a mock code sample which might make clear what I am trying to achieve:
char *message = "test message";
int length = strlen(m开发者_开发知识库essage);
int fd = open(file, O_CREAT|O_RDWR);
write(fd, length??, ??); // <--- what goes here
write(fd, message, length);
I dont care about platform independence and byte order, just that it can compile on as many platforms as possible.
sizeof(length)
goes in the field.
It is preferable over using sizeof(int)
in case you ever change the type of length
in the future.
sizeof
expresses the, well, size of a data type in multiples of sizeof(char)
, which is always 1.
sizeof is your friend.
write(fd, &length, sizeof(int));
sizeof(int) = 4 (on Linux, 32 & 64 Bit x86-Architecture)
sizeof(long) is 4 on 32 Bit, 8 on 64 Bit (on Linux, x86-32/64-Architecture)
Dunno about Windows.
write(fd, &length, sizeof(length));
You can use sizeof
with variable names or type names. In this case you could have done sizeof(int)
.
The write
function takes the address of the memory zone you want to write, so you use the &
(address of) operator. You don't have to do it for the string because you already have a pointer (char*
).
精彩评论