Home > OS >  Erase bytes in file in C
Erase bytes in file in C

Time:11-13

Can I erase last byte or bytes in file without creating new file and changing names?

For example, file contains "00 00 AB" and i need erase "AB". At the end, file contains only "00 00".

CodePudding user response:

Since C 17 we have the file system library that allows

#include <filesystem>

int main() {
  std::filesystem::path p("somefile");

  auto size = std::filesystem::file_size(p);
  std::filesystem::resize_file(p, size - 1);
}

If the new size is larger than the old, the file will be filled with zero-bytes, otherwise it's truncated.

CodePudding user response:

It resizes file to 2 byte from any size and truncates remain data. "00 00 AB" -> "00 00"

#include <filesystem>
int main(){
    std::filesystem::resize_file("test.dat", 2);
}
  •  Tags:  
  • c
  • Related