I'm learning File I/O at the moment but having an issue reading from/writing to a file. My program compiles but says that it can't find the .txt file to open.
I've tried to troubleshoot by creating a new .txt file to write to and making sure the location of the two files are the same but can't even find that output file!?
#include <iostream>
#include <cstdlib>
#include <fstream> //need this class for new streams
#include <string>
usingnamespace std;
int countLines(string fileName){
int counter = 0;
string myLine;
//declaring the stream variable myFile(what I want it to read from, the open mode I want)
ifstream myFile;
ofstream myFileOut;
myFile.open("SampleInput.txt");
myFileOut.open("Output.txt");
myFile >> myLine;
//check to see if file was opened correctly
if (myFile.fail()){
cout << "Error opening "<< fileName << endl;
return 0;
}
//while loop until the end of file is reached
while (!myFile.eof()){
//getline(what I want to read from, where I want to store it)
getline(myFile, myLine);
counter++;
cout << counter;
}
myFile.close();
return counter;
}
int main(){
int countedLines = countLines("SampleInput");
cout << countedLines << endl;
return 0;
}
Well, I see where you read the file, line 28, increase and print out, a counter, lines 29 and 30, but nowhere do I see where you write to a file, so, nothing would be created.
There's a typo in your code. Line 38 int countedLines = countLines("SampleInput");
should become: int countedLines = countLines("SampleInput.txt");
Then you can change line 16 from myFile.open("SampleInput.txt");
to myFile.open(fileName);
Now your file, if exists, will be opened, but after (line 18) myFile >> myLine;
ios::fail will return "false". You can try to comment it out to verify it.
Sorry, I didn't answer your question: on my Ms W7 machine Code::Blocks opens SampleInput.txt if it's in the project folder, i.e. where's the ".cbp" file. If you don't solve your problem, I can check on a Linux environment.