Jack
Jack

Reputation: 16724

how to write non-char* by using write() function?

it's possible to write non-char* by using write() function? I need to print a unsigned long and I have no idea how to do it. In other words, pass a unsigned long in buf parameter.

Upvotes: 0

Views: 734

Answers (1)

paxdiablo
paxdiablo

Reputation: 882806

It's usually preferable to use the standard C functions where available since they're more portable. If you can, and you want to output it as text, you should look at fprintf rather than fwrite. The former will format it for you, the latter is meant for writing raw memory blocks.

For example:

int val = 42;
fprintf (fh, "%d", val); // should check return value.

will output the text "42".

If you do want to write out the binary representation, fwrite is the means for that:

int val = 42;
fwrite (&val, sizeof (val), 1, fh); // should check return value.

That will write out the binary representation so that the bytes 0, 0, 0 and 42 are written to the file (depending on what the memory layout is for an int variable of course - it may vary depending on the implementation).


That's if you're able to use file handles rather than descriptors, otherwise the f* functions are no good for you. There may be valid reasons why you want to work with the lower levels.

So, if all you have is a descriptor for write, you'll need to format the variable into a string first, with something like:

char buff[100];
sprintf (buff, "%d", val);
write (fd, buff, strlen (buff)); // should check return value.

That's assuming you want it as text. If you want it as a binary value, it's similar to the way we've done it above with the fwrite:

write (fd, &val, sizeof (val)); // should check return value.

Upvotes: 1

Related Questions