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

前端 未结 3 1938
天命终不由人
天命终不由人 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.

提交回复
热议问题