HW Problem - Where exactly is my output file from Code::Blocks

Write your question here.

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!?

Do I need to have them saved in a specific spot?

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
#include <iostream>
#include <cstdlib>
#include <fstream> //need this class for new streams
#include <string>
using namespace 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;
}
@mongoliancowboy

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.

Good luck!
Last edited on
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.
Topic archived. No new replies allowed.