C - 在编写之前构建我的字符串

时间:2013-10-04 17:16:56

标签: c file c-strings string-building

我对C很新,并且实现了一个将稀疏矩阵写入文件的函数。 我想知道在将C写入文件之前,在C中构建字符串的正确方法是什么。

我目前正在调用write(),导致效果不佳。我必须格式化字符串并在循环内按顺序构建它。在Java中我会使用StringBuilder,但我不知道C等价物。

这是我想做的简化版

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));
}

这样做的C方法是什么?

2 个答案:

答案 0 :(得分:1)

  

我目前正在调用write(),导致很差   性能。

你需要做一些缓冲,因为与#34; normal"相比,系统调用是昂贵的。操作

  • 您可以简单地使用标准库 - 获取FILE *并致电 fwrite - 这将自动执行缓冲

  • 您可以使用mempcy和朋友附加到缓冲区来进行自己的缓冲。当缓冲区填满时,您只需执行大型write

  • 即可

我会首先尝试stdio方法,因为它更容易。如果您想知道如何从文件描述符中获取FILE *,请查找POSIX标准fdopen

答案 1 :(得分:1)

主要是sprintf()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);
相关问题