copy file

I have two files

The first file:
1
2
3
4
5
6
7
// first.cpp
#include <iostream.h>
int main()
 {
      cout <<"hello world";
      return 0;
 }


The second file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// second.cpp
#include <iostream.h>
#include <fstream.h>

#define fn "first.exe"  // filename

int main()
 {
      fstream fin(fn, ios::in | ios::binary);
      fstream fout("copy.exe", ios::out | ios::binary);
      
      if(fin == NULL || fout == NULL) {
         cout <<"error";
         return 1;
      }
      
      // read from the first file then write to the second file
      unsigned char c;
      while(!fin.eof())
       {
            fin >> c;
            fout << c;
       }
      
      return 0;
 }


I compiled both of them
the next step I run second.exe file, it makes copy.exe file but the copy.exe file doesn't work?

Can anybody explain the problem?
Tnanks you very muck !
The >> stream operator reads formatted input and so it will
skip some characters when reading the file.
If you check the file sizes you will see that copy.exe is SMALLER
than the original file first.exe.

You need to use unformatted input/output (get and put) , so your code now looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// second.cpp
#include <iostream.h>
#include <fstream.h>

#define fn "first.exe"  // filename

int main()
 {
      fstream fin(fn, ios::in | ios::binary);
      fstream fout("copy.exe", ios::out | ios::binary);
      
      if(fin == NULL || fout == NULL) {
         cout <<"error";
         return 1;
      }
      
      // read from the first file then write to the second file
      char c;
      while(!fin.eof())
       {
            fin.get(c);
            fout.put(c);
       }
      
      return 0;
 }
Last edited on
On another note:
You should be using the new style c++ headers

For example:
Use iostream not iostream.h.

If your compiler does not allow this then you need to update your compiler because it is out of date.
As you said

The >> stream operator reads formatted input and so it will
skip some characters when reading the file."


So the characters it will skip? for example?
So, how do the get() method and the put() method work?

Thank for your reply!
>> will skip things like Carriage Returns, Linefeeds, spaces, tabs (non character items).
So your copy will be corrupt.

get will read whatever is there.

So to get an exact copy use get to read the file.

>> is more for getting text items - for example if you want to read words, letters, strings, numbers

Last edited on
Topic archived. No new replies allowed.