fstream fail open file

hi,
in this simple program to learn the i / o on files, the code works, but it always fails to open the file.
what determines the success of the call of the function member

test_file.open () ?

i use C :: B

thanks in advance.
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
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string t_stream;
    fstream test_file;

    test_file.open( "testfile.txt", ios::in | ios::out );

    if ( test_file.is_open() )
    {
        while ( test_file.good() )
        {
            getline( test_file, t_stream );
            cout << t_stream << endl;
            test_file << " why dont open the file ? " << endl;
        }
        test_file.close();
    }
    else
        cout << " unable to open file " << endl;
    return 0;
}
It worked for me. It opened the file and printed, "why dont open the file ?" and then closed file and exited program. Is that what it is supposed to do?
Have you created a text file called "testfile" with the necessary information in it.
@ pnoid:
yes, but on my computer the output is "unable for the open file"
OK, I created the test file before I ran the program, sorry I assumed you did too. You have to create the file before you run it.
ar2007, If you use VC++, you may need to place the file in the project directory instead of the executable directory. The issue is the change in working directory.
@ L B:
i use code::blocks 12.11

can you explain better?
other opinion ?
put the file in the folder that your executable is in.
do you mean that I have to first create the file "testfile.txt"
and then use it in code?
I guess that's what they're saying.
ok sorry.

thx at all
See, the "testfile.txt" file should be in the same location as your code, if your code is under a folder called Texts then your" testfile.txt" file should also be in there......same location

hope this helps
Last edited on
Some explenation why it did not work.
Your say test_file.open and then ( "testfile.txt", ios::in | ios::out ); The "testfile.txt" basically says the Programm
"Look for a testfile.txt File in the folder of the .exe. Is it there?"
Last edited on
Topic archived. No new replies allowed.