I'm quite new to C and implementing a function that writes a sparse matrix to a file. I'm wondering what the correct way is in C to build a string before I write it to the file.
I'm currently calling write()
a lot which results in poor performances. I have to format the string and build it sequentially inside a loop. In Java I would use a StringBuilder
but I don't know the C equivalent.
Here's a simplified version of what I wanna do
int i;
unsigned int u;
for(i=0 ; someCondition ; i++) {
if(someOtherCondition)
dprintf(fileDescr, "I need to write this unsigned int %u\n", u);
else
write(fileDescr, "0", sizeof(char));
}
What's the proper C way to do this?
I'm currently calling write() a lot which results in poor performances.
You need to do buffering as systems calls are expensive compared to "normal" operations.
You could simply use the standard library - get a FILE *
and call
fwrite
- this will automatically do buffering
You could to your own buffering by appending to a buffer, using mempcy
and friends. When the buffer fills you could simply do a large write
I would first try the stdio
approach as it's easier. If you're wondering how to get a FILE *
from a file descriptor, look for the POSIX-standard fdopen
.