I'm trying to write a bitmap file to the browser in C. I can write the printable ascii parts like this,
write (socket, "BM", 2);
but how do I write the non-printable ones with their decimal value? I know that if I was writing to a file I could use something like this,
fprintf(fp, "%c%c%c%c" , 40,0,0,0);
But I don't know how to do the same thing but instead just write it to the socket... Please help me out, thank开发者_开发百科s.
You can wrap a file descriptor in a FILE
structure (thus enabling use of all the printf
family) using fdopen()
:
int fd = socket(...);
FILE *fp = fdopen(fd, "w+");
Now, fp
is just like any other FILE*. Cheers!
If the bytes you want to write are static, you can simply define a buffer and use it...
char buffer[]={40,0,0,0};
write(socket, buffer, sizeof(buffer));
or inline...
write(socket, (char[]){40,0,0,0}, 4);
The best approach depends where the characters are coming from (are they dynamic / are they already in a buffer), how many there are, whether or not you want to do encoding, where the size element comes from.. etc etc..
You can use sprintf
for that.
char data[4];
sprintf(data, "%c%c%c%c", 40, 0, 0, 0);
write(socket, data, 4);
EDIT:
If you'r using this a lot, you can write your own function for formated write to socket like this:
void writef(int socket, const char * format, ...) {
char buffer[1024];
va_list args;
va_start(args, format);
int length = vsprintf(buffer, format, args);
va_end(args);
write(socket, buffer, length);
}
and then you can simply call writef(socket, "%c%c%c%c", 40, 0, 0, 0);
You could snprintf
the values into a char buffer, and then write
out the buffer.
精彩评论