什么是覆盖在C零整个文件的最快方法? [英] What is the fastest way to overwrite an entire file with zeros in C?
问题描述
我需要做的是用最快的方式零填满整个文件内容。我知道像 CP
一些Linux命令实际上得到什么是最好的块大小信息在同一时间写的,但如果使用该块大小信息,我无法弄清楚足有一个不错的表现,看起来像 st_blksize
从 STAT()
不给我块尺寸。
谢谢!
What I need to do is to fill the entire file contents with zeros in the fastest way. I know some linux commands like cp
actually gets what is the best block size information to write at a time, but I wasn't able to figure out if using this block size information is enough to have a nice performance and looks like the st_blksize
from the stat()
isn't giving me that block size.
Thank you !
一些答案的评论:
-
这需要在C语言中进行,而不是像使用公用事业一丝一毫
This need to be done in C, not using utilities like shred.
有在的使用情况统计()
st_blksize
正在恢复比文件大小大的块,
不知道我该怎么处理这个问题。
st_blksize
is returning a block greater than the file size,
don't know how can I handle that.
使用截断()/ ftruncate(),只额外的空间填充有
零,我需要覆盖的全部的文件数据。
Using truncate()/ftruncate(), only the extra space is filled with zeros, I need to overwrite the entire file data.
我想在这样的:
fd = open("file.txt", O_WRONLY);
// check for errors (...)
while(TRUE)
{
ret = write(fd, buffer, sizeof(buffer));
if (ret == -1) break;
}
close(fd);
的问题是如何定义的最佳缓冲器大小编程
The problem is how to define the best buffer size "programmatically".
推荐答案
速度最快,最简单的:
int fd = open("file", O_WRONLY);
off_t size = lseek(fd, 0, SEEK_END);
ftruncate(fd, 0);
ftruncate(fd, size);
显然,这将是很好的补充一些错误检查。
Obviously it would be nice to add some error checking.
这是解决方案的不可以你想要的文件的安全闭塞虽然。它将简单地标记由文件为未使用用过的旧的块,并留下一个稀疏文件不占用任何物理空间。如果你想从物理存储介质清除文件的旧内容,你可以尝试这样的:
This solution is not what you want for secure obliteration of the file though. It will simply mark the old blocks used by the file as unused and leave a sparse file that doesn't occupy any physical space. If you want to clear the old contents of the file from the physical storage medium, you might try something like:
static const char zeros[4096];
int fd = open("file", O_WRONLY);
off_t size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
while (size>sizeof zeros)
size -= write(fd, zeros, sizeof zeros);
while (size)
size -= write(fd, zeros, size);
您可以增加零
的规模达32768左右,如果测试显示,它可以提高性能,但超过一定点不应该帮助,将只是一个浪费。
You could increase the size of zeros
up to 32768 or so if testing shows that it improves performance, but beyond a certain point it should not help and will just be a waste.
这篇关于什么是覆盖在C零整个文件的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!