read text write binary

I am planning to use this mostly to copy binary files, but why won't this work with text???

input.txt

this is a test


code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main(int argc, char* argv[]) {
  // open file                                                                                                                                                                    
  std::ifstream ifs;
  ifs.open("./input.txt", std::ios::binary);
  ifs.seekg(0, std::ios::end);
  int totalLength = (int) ifs.tellg();

  // read data                                                                                                                                                                    
  char* fileBuffer = new char [totalLength];
  ifs.read(fileBuffer, totalLength);
  ifs.close();

  // write data                                                                                                                                                                   
  std::ofstream ofs;
  ofs.open("./output.txt", std::ios::binary);
  ofs.write(fileBuffer, totalLength);
  ofs.close();

  return 0;
}


output.txt
\310^?z^@^@^@^@^@\300\367\346^A^@



Will this method always work to copy a file?
Last edited on
At this point:

ifs.read(fileBuffer, totalLength);

the get pointer is at the end of the file. After finding the totalLength you should move it back to the beginning of the file:

ifs.seekg (0, ios::beg);

Will this method always work to copy a file?

It won't work for very large files, i.e. files who are bigger than the heap / free store will allow.
ooohhhhh... you caught my bug! Thanks!
Topic archived. No new replies allowed.