0

I'm writing chucks of chat *ptr into file, but it takes me so long to finish. I don't know why.

for(int i = 1; i < 64048; i++){
    if(ptr[i] != NULL){
        fwrite(ptr[i], 1, strlen(ptr[i])-6, file);
        free(ptr[i]);
    }
}

there is array of char pointers storing 8186 bytes, and I want to write into file, but the time is so long.

I have 64048 chunks of string need to write into file.

What could cause the slowing fwrite() ??

thank you

4

1 回答 1

3

OP 使用错误的方法来调整大小fwrite(),以及其他小错误。

如果“存储 8186 字节的 char 指针数组”表示
1 每个char数组有 8186 个有效字节的数据,使用大小 8186。
2 每个char数组都是 NUL 终止的字符串,那么需要进行测试以确保每个数组的长度至少为 6。不是确定这 6 是什么。笔记:size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream )

我怀疑当小于 6时 OP- 6会导致问题。这会使负差异非常大,通常是 unsigned for in 。strlen(ptr[i])size_tcountfwrite()

for(int i = 0; i < 64048; i++){  // start at 0
    if(ptr[i] != NULL){
        int result; 

        result = fwrite(ptr[i], 1, 8186, file);
        if (result != 8186) ; handle error;

        // or

        size_t len = strlen(ptr[i]) + 1; /// Add 1 for the NUL byte
        if (len < 6) ; handle error of whatever the OP's 6 is about.
        result = fwrite(ptr[i], 1, len, file);
        if (result != len) ; handle error;

        free(ptr[i]);
    }
}
于 2013-09-15T03:10:14.377 回答