3

I've just started learning C++, and I'm working on a program that is supposed to grab an image from the hard disk and then save it as another name. The original image should still remain. I've got it work with text files, because with those I can just do like this:

ifstream fin("C:\\test.txt");
ofstream fout("C:\\new.txt");

char ch;
while(!fin.eof())
{
    fin.get(ch);
    fout.put(ch);
}

fin.close();
fout.close();
}

But I suppose that it's not like this with images. Do I have to install a lib or something like that to get it work? Or can I "just" use the included libraries? I know I'm not really an expert of C++ so please tell me if I'm totally wrong.

I hope someone can and want to help me! Thanks in advance!

Btw, the image is a .png format.

Mike Corcoran
  • 12,622
  • 4
  • 31
  • 46
GuiceU
  • 940
  • 6
  • 18
  • 34

3 Answers3

7

You can use the std streams but use the ios::binary argument when you open the stream. It's well documented and there is several examples around the internet

Emil
  • 86
  • 1
2

You are apparently using MS Windows: Windows distinguishes between "text" and "binary" files by different handling of line separators. For a binary file, you do not want it to translate \n\r to \n on reading. To prevent it, using the ios::binary mode when opening the file, as @Emil tells you.

BTW, you do not have to use \\ in paths under windows. Just use forward slashes:

ifstream fin("C:/test.txt");

This worked even back in WWII using MS-DOS.

Community
  • 1
  • 1
wallyk
  • 53,902
  • 14
  • 79
  • 135
0

If the goal is just to copy a file then CopyFile is probably better choice than doing it manually.

#include <Windows.h>
// ...
BOOL const copySuccess = CopyFile("source.png", "dest.png", failIfExists);
// TODO: handle errors.

If using Windows API is not an option, then copying a file one char at a time like you have done is very inefficient way of doing this. As others have noted, you need to open files as binary to avoid I/O messing with line endings. A simpler and more efficient way than one char at a time is this:

#include <fstream>
// ...
std::ifstream fin("source.png", std::ios::binary);
std::ofstream fout("dest.png", std::ios::binary);
// TODO: handle errors.
fout << fin.rdbuf();
sdkljhdf hda
  • 1,327
  • 8
  • 17