如何重用数组来快速写入C中的大文件

时间:2015-08-31 14:18:31

标签: c arrays

我正在尝试快速写入一个大文件并使用数组。所以我必须多次使用相同的数组。我的计划的一部分如下。

    char buff[1024];
    char *x= buff;
    fd = open("file.txt",O_CREAT|O_RDWR, S_IRWXU) ;


    void function(){

        char temp[128];
        sprintf(temp,"%s,%s,%d\n",src,dst,payload) ;
        x=myStrCat(x,temp); // copy files from temp to buff

        //This is my question. if the buffer "buff" is full, how to  truncate the buffer for next loop and that too fast.
        if (strlen(buff) >= 1024){
            write(fd,buff, len);
        }
    }

    char * myStrCat(char * dest, char * src){
             while(*dest) dest++;
             while( *dest++ = *src++);
             return --dest;

     }

    int main(){
        //other codes
        while (true){        
            function();
            //conditions to break the loop untill then function() will be continuously in loop.
        }
        return 0;
    }

提前致谢!

2 个答案:

答案 0 :(得分:2)

strlen(buf)永远不会是> = 1024,因为您只为其分配了1024个字节。 C字符串最后需要NULL,因此您将获得缓冲区溢出,从而导致未定义的行为。但是你可以有1023 + NULL。

您的代码不会检查myStrCat中是否存在缓冲区溢出。它会导致未定义的行为。如果您已经有1020个字符并且想要添加另外10个字符怎么办?

您应该这样做的方法是保留一个数字,表示缓冲区中已有的字符数。如果缓冲区不能保存下一个字符串,则将数据写入文件并将字符数归零。如果可以,将字符串从字符计数指示的位置开始复制到缓冲区,然后获取下一个字符串。

当然最后将缓冲区中的内容写入文件。

这样您就不会超过缓冲区限制。

(你确定这比让操作系统处理写缓存要快得多吗?)

答案 1 :(得分:0)

也许你正在寻找像这样的东西:

    #define BUFFER_SIZE 1024

char buff[BUFFER_SIZE];
uint16_t buff_len = 0;

void function(){

    char temp[128];
    int len = sprintf(temp,"%s,%s,%d\n",src,dst,payload) ;

    if ((len+buff_len) > BUFFER_SIZE-1)
    {
        write(fd,buff, buff_len);

        buff_len = 0;
    }


    strcpy(&buff[buff_len],temp); // copy files from temp to buff

    buff_len += len;
}