What is the most efficient quickest way to write all zeros to a file? including error checking. Would it just be fwrite? or is fseek involved?
I've looked elsewhere and saw code similar to this:
off_t size = fseek(pFile,0,SEEK_END);
fseek(pFile,0,SEEK_SET);
while (size>sizeof zeros)
size -= fwrite(&address, 1, sizeof zeros, pFile);
while (size)
size -= fwrite(&address, 1, size, pFile);
where zeros is an array of file size I suspect. Not sure exactly what off_t was because it wasn't directly intuitive to me anyways
Do you want to replace the contents of the file with a stream of binary zeroes of the same length, or do you want to simply empty the file? (make it have length zero)
Either way, this is best done with the OS file I/O primitives. Option one:
char buf[4096];
struct stat st;
int fd;
off_t pos;
ssize_t written;
memset(buf, 0, 4096);
fd = open(file_to_overwrite, O_WRONLY);
fstat(fd, &st);
for (pos = 0; pos < st.st_size; pos += written)
if ((written = write(fd, buf, min(st.st_size - pos, 4096))) <= 0)
break;
fsync(fd);
close(fd);
Option two:
int fd = open(file_to_truncate, O_WRONLY);
ftruncate(fd, 0);
fsync(fd);
close(fd);
Error handling left as an exercise.
mmap() and memset()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With