Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero'ing out a file

Tags:

c

file-io

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

like image 692
Questioneer Avatar asked Jan 18 '23 11:01

Questioneer


2 Answers

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.

like image 126
zwol Avatar answered Jan 21 '23 02:01

zwol


mmap() and memset()

like image 33
Martin Beckett Avatar answered Jan 21 '23 00:01

Martin Beckett