Help with copying one file to another file I/O help please!

I'm having some trouble with copying one I/O stream into another. I've put the first one into an array but I cannot get my second prompt to copy the .txt file the first prompt sees and outputs to the console. When I try and grab the info from the .txt file my first prompt sees I only see blank space in my .txt file. Could anyone please point me in the right direction? I've been stuck on this problem for hours :(

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <fstream>
using std::ifstream;
using std::ofstream;

int main()
{
  while(1)
  {
    ifstream fin;  
    char buf[512]; //large string array
	char buff[512]; //second array for promt 2
			        
    cout << "Enter the name of the file you want to open: ";
	cin.getline(buf,512);
	
	cout << "Enter a filename to copy the first file to: ";
	cin.getline(buff,512);
	
    fin.open(buf); //open iocopy.txt
    		
    if (!fin.good()) break; //test for failure
    
	 while(fin.getline(buf,512)) //loop to read the file (w/ large string array)
     cout << buf << endl;
	
	ofstream fout;
	fout.open(buff);
	fin.open(buf);
	fout << buff << endl;

	 while(fin.getline(buff,512))
	cout << buff << endl;

    fin.close();
    
    if(fin.eof()) break; //breaks when the end is reached

  }
  

  
  
  
  
}

This code does as follows:

1. Reads in two file names (lines 18-22).
2. Then copies data line by line from fin to stdout (lines 24-29). This would usually display on your tty.
3. An output file named with the second file name the user entered will be opened (lines 31-32).

Now things become somewhat confusing:
4. A file named by the string as read in by the last getline() statement in line 28 will be opened. There may be a great chance, that no such file exists, so that line 33 would fail.
5. Now you write the second file name the user initially entered into the output file you've opened in line 31-32 (line34).
6. Lines 36-37 will fail because opening fin may have failed in line 33 (see above).

7. ...


To copy the contents of one file to another you may

1. Open the source (fin) for input (like in line 24).
2. Open the destination (fout) for output (like in line 32).
3.1. Enter a loop reading line by line until eof or error (like line 28).
3.2. After reading a line you should write it to your output file:

1
2
while (fin.getline(buf, 512))
    fout << buf << endl;



4. Finally after leaving the loop you should close fin and fout.

That's it!
Topic archived. No new replies allowed.