我正在尝试快速写入大文件并使用数组。所以我必须多次使用同一个数组。我的部分程序如下。
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;
}
提前致谢!
最佳答案
strlen(buf)
永远不能 >= 1024,因为您只为它分配了 1024 个字节。 C 字符串要求末尾为 NULL,因此您将遇到缓冲区溢出,从而导致未定义的行为。不过,您可以使用 1023+NULL。
您的代码也不会检查 myStrCat
中是否会出现缓冲区溢出。它会导致未定义的行为。如果您已经有 1020 个字符并想再添加 10 个怎么办?
你应该这样做的方法是保留一个数字来指示缓冲区中已有的字符数。如果缓冲区不能容纳下一个字符串,则将数据写入文件并将字符数归零。如果可以,则从字符数指示的位置开始将字符串复制到缓冲区并获取下一个。
当然最后把buffer中的内容写入文件。
这样您就不会超出缓冲区限制。
(你确定这会比让操作系统处理写缓存快很多吗?)
关于c - 如何重用数组以非常快地写入 C 中的大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32313443/