Program won't display content of the file specified

Hello, every time i try to open a text file to display the content, it will create another blank file with the same name as the file that i am trying to open.

In the case below, I used strings and a loop to display all the content of a file(that already exists). I'm sure there's a glitch somewhere. Any help would be appreciated.



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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main ()
{
    string string1;
    fstream file;
    file.open("data.txt", ios::in | ios::out | ios::app);

    if (file.is_open())
    {
        cout << "File has successfully been opened" << "\n";
    }

    else
       {
     cout << "Error, could not open file" << "\n";
        }

        cout << "Here is the content of the file;


   while (getline (file , string1))
         {
          cout << string1 << "\n";
         }



file.eof();

} 




I am trying to open the file data.txt, it's content consists of a list of student names and their classroom numbers. But every time i try to open this specific file, it creates another one with the same name. What am I doing wrong here?
Last edited on
The code works fine for me.
Reads the file and does not create any new file.

Verify that you have this data.txt in the same directory where you compile the code.
Thank you for your response shadow.

How can I verify if the file is in the same directory?

Do I have to store the file in a sub-folder of CodeBlocks? (by the way, I am using CodeBlocks to compile)
Last edited on
Never mind, I figured it out.

Thank you.
when you open a new file to write you code, you save the file somewhere right?
The data.txt should be in the same directory where you saved your code.

Topic archived. No new replies allowed.