Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

mostly sprintf() and realloc().

// all error checks omitted for clarity, you are NOT allowed to do this
size_t allocsz = 0x40;
size_t len = 0;
char *buf = malloc(allocsz); // initial buffer size

for (; someCondition; i++) {
    int n = snprintf(
        NULL, 0,
        "Format %s so that it %s with %u", "this", "works", 1337u
    );

    if (len + n >= allocsz) {
        while (len + n >= allocsz) { // exponential storage expansion
            allocsz *= 2;
        }

        buf = realloc(buf, allocsz);
    }

    snprintf(
        buf + len, n + 1,
        "Format %s so that it %s with %u", "this", "works", 1337
    );

    len += n;
}

write(fd, buf, len);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top