What is the fastest way to overwrite an entire file with zeros in C?

前端 未结 3 1939
天命终不由人
天命终不由人 2021-01-03 05:35

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 siz

相关标签:
3条回答
  • 2021-01-03 06:03

    With mmap (and without error checking):

    stat(filename,&stat_buf);
    len=stat_buf.st_size;
    fd=open(filename,O_RDWR);
    ptr=mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    memset(ptr,0,len);
    munmap(ptr,len);
    close(fd);
    

    This should use the kernel's idea of block size, so you don't need to worry about it. Unless the file is larger than your address space.

    0 讨论(0)
  • 2021-01-03 06:27

    Fastest and simplest:

    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);
    

    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.

    0 讨论(0)
  • 2021-01-03 06:29

    This is my idea; notice I removed every error checking code for clarity.

    int f = open("file", "w");             // open file
    int len = lseek(f, 0, SEEK_END);       // and get its length
    lseek(f, 0, SEEK_BEG);                 // then go back at the beginning
    char *buff = malloc(len);              // create a buffer large enough
    memset(buff, 0, len);                  // fill it with 0s
    write(f, buff, len);                   // write back to file
    close(f);                              // and close
    
    0 讨论(0)
提交回复
热议问题