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

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

提交回复
热议问题