# c++ fopen/fclose question

This topic is 3287 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello , i just stumbled upon a problem for wich i have no solution. I have a binary and i decide to remove half of the file. Lets say i want to remove the first half of the file. I copied the other half of the file and moved in the new place from the beginning of the file. The problem is that the original file dosen't shrink in size, if my file was 2 KB and i removed the first half i don't know to resize the file on the HDD to 1 KB. Is there a solution for this? (other than creating a new file/deleting the old/renaming the new ?) I used standard fopen/fclose/fread/fwrite for file handling. Thanks, Makaan

##### Share on other sites
Quote:
 Original post by MakaanIs there a solution for this? (other than creating a new file/deleting the old/renaming the new ?)I used standard fopen/fclose/fread/fwrite for file handling.
Nope, there's no solution using the C or C++ file functions.

If you were using Win32, then you could use SetEndOfFile, but that's the only option aside from deleting and re-creating the file.

Thanks.

##### Share on other sites
For Posix, there's also ftruncate & truncate.
Also found this:
Quote:
 not sure if this helps but if you fseek to the position where youwish to truncate to then write 0 bytes the file will be truncated.

##### Share on other sites
If you're using C++, then fopen() etc. are nominally "standard", but are quite old-fashioned and don't really have a place in newly written code. They belong to C.

With the new stream classes found in <fstream>, you can specify whether an output file stream (analogous to the old FILE *, except that it's not a pointer) will "truncate" (i.e. clear all the existing file contents before you start writing new stuff) or not (i.e. append to the existing file).

Something like this should do the trick:

#include <iostream>#include <fstream>#include <vector>#include <string>#include <iterator>#include <algorithm>void remove_first_half(const std::string& file_name) {  std::vector<char> file_contents;  using std::ios_base::binary;  // Open the file to read it.  {    std::ifstream file_in(file_name.c_str(), binary);    // Read the whole file into the buffer    std::istreambuf_iterator<char> file_start(file_in), file_end;    std::copy(file_start, file_end, std::back_inserter(file_contents));  } // The file is automatically closed here.  // Get an iterator to the midpoint of the file data.  std::vector<char>::iterator file_middle = file_contents.begin();  std::advance(file_middle, file_contents.size() / 2);  // Reopen the file to write it.  {    // IIRC, truncation is the default behaviour, so we just have to specify    // that it's a binary file. :)    std::ofstream file_out(file_name.c_str(), binary);    std::copy(file_middle, file_contents.end(), ostreambuf_iterator<char>(file_out));  }}