Zero from file

What is the most efficient way to write all zeros to a file? including error checking. Will it just be a flirt? or is fseek used?

I 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 the file size array I suspect. Not sure exactly what off_t is, because it was uninteresting to me anyway

+4
source share
2 answers

Do you want to replace the contents of the file with a stream of binary zeros of the same length or just want to delete the file? (make it equal to zero)

In any case, this is best done with the input / output primitives of the OS files. Option 1:

 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 on the left as an exercise.

+5
source

mmap () and memset ()

+4
source

All Articles