I have a menu that that starts some methods based on user's choice. Two of the methods however don't work properly, and I have no idea why. This is the part of the menu for them:
case 2:
{
string fileName;
cout << "Which file to read?:";
cin>>fileName;
this->ReadFromFile(fileName);
break;
}
case 3:
{
string fileName;
cout << "Enter name for the file:";
cin>>fileName;
this->WriteToFile(fileName);
break;
}
Here are the methods:
void ReadFromFile(string file)
{
string line;
ifstream rfile ("FileSystem/" + file);//open file for reading
if (rfile.is_open())
{
while(getline(rfile, line))
{
cout << line << endl;
}
}
else
{
cout << "An error occurred when tried to read from this file." << endl;
}
rfile.close();
_getch();
}
void WriteToFile(string fileName)
{
ofstream myFile;
ifstream exists (fileName);//open read stream to check if file exists
if(exists)//returns true if file can be opened and false if it cant
{
exists.close();//close the stream
myFile.open(fileName, ios_base::app);// open file for reading(ostream)
}
else
{
exists.close();
CreateFile(fileName);//file doenst exists, so we create one and list it in the file tree
myFile.open("FileSystem/" + fileName, ios_base::app);// open file for reading(ostream)
}
if(myFile.is_open())
{
string input;
cout << "start writing and press enter to finish. It will be done better later." << endl;
cin>>input;
myFile << input;
}
else
{
cout<<"An error occurred when tried to open this file."<<endl;
}
myFile.close();
_getch();
}
Now here is the funny part. When I try to write something to a file, it doesn't matter that I open it with: 'ios_base::app' or 'ios:app' it just rewrites it. But it cant even do that properly. If i have a line with whitespaces like'Hi this is me.' for example, it only writes the first word, which here is 'Hi'. So if I then decide to read the file the first thing that happens is that it says that the file cant be oppened, even before it asks me for a name. That happens the first 3 tries and then the reading magically works. I have bashed my head into this for the last two hours and I still cant understand what is happening. Can anyone please explain this to me, and show me my mistakes?