Jan 30, 2016 at 1:09am UTC
My goal is to input the first line of a file into another file only if the input file exists and the output file doesn't. I have accomplished the status check of the input file, however, my code will still input the line into an already existing file. If the output file already exists, I want the program to terminate. Here is what I have:
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
#include "main.h"
using namespace std;
int main()
{
fstream inFile;
fstream outFile;;
string fileName("" );
string destName("" );
cout << "Please enter file name: " ;
cin >> fileName;
cout << endl;
inFile.open(fileName, ios::in);
getline(inFile, fileName);
if (inFile.good() != true ) {
cout << "File does not exist!\n" << endl;
return 0;
}
cout << "Please enter file name of destination: " ;
cin >> destName;
cout << endl;
outFile.open(destName, ios::out);
if (outFile.good() == true ) {
cout << "File '" << destName << "' already exists!\n" << endl;
return 0;
}
outFile.open(destName, ios::out);
outFile << fileName << endl;
inFile.close();
outFile.close();
return 0;
}
Since I'm trying to learn too, can you please add an exe!planation of what I did wrong? Thank you in advance!
Last edited on Jan 30, 2016 at 1:31am UTC
Jan 30, 2016 at 1:30am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream inFile;
inFile.open("Test.txt" );
if (inFile.good() != true )
{
cout << "File does not exist!\n" << endl;
// Ok to open as output file
}
else
{
cout << "File exist!\n" << endl;
inFile.close();
}
return 0;
}
Last edited on Jan 30, 2016 at 1:31am UTC