fstream fail open file

Aug 19, 2013 at 8:39pm
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;
}
Aug 19, 2013 at 8:49pm
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?
Aug 19, 2013 at 8:51pm
Have you created a text file called "testfile" with the necessary information in it.
Aug 19, 2013 at 8:54pm
@ pnoid:
yes, but on my computer the output is "unable for the open file"
Aug 19, 2013 at 8:58pm
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.
Aug 19, 2013 at 8:59pm
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.
Aug 19, 2013 at 9:02pm
@ L B:
i use code::blocks 12.11

can you explain better?
Aug 19, 2013 at 9:50pm
other opinion ?
Aug 19, 2013 at 9:58pm
put the file in the folder that your executable is in.
Aug 19, 2013 at 10:09pm
do you mean that I have to first create the file "testfile.txt"
and then use it in code?
Aug 19, 2013 at 10:16pm
I guess that's what they're saying.
Aug 19, 2013 at 10:20pm
ok sorry.

thx at all
Aug 19, 2013 at 10:27pm
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 Aug 19, 2013 at 10:27pm
Aug 19, 2013 at 10:46pm
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 Aug 19, 2013 at 10:46pm
Topic archived. No new replies allowed.