So file i/o is completely useless?

You open up a file and take its data and use it in your program...except for the fact that when you open a file it's always empty?????

I have this in one program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
using namespace std;

#include "Student.h"

main()
{
        ofstream myFile;
        myFile.open("Student.dat");

        if(myFile == NULL)
        {
                cerr << "error" << endl;
        }

        myFile << "Steven J Caulfield 14 325-5454-34";

        myFile.close();

}       


And then, in a separate program I have this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
using namespace std;

#include "Node.h"


const string delete_Name = "q";

main()
{
        ofstream ofh;
        ifstream ifh;

        string student;

        ifh.open("Student.dat");
        ifh >> student;
        cout << student << endl;
}


Execution of this second program yields a blank line, despite the fact that I opened the same file as the one in the previous program, which has student information in it.

So what am I doing wrong?
Are both programs using the same working directory?

The second program does not check ifh.is_open() or other test for the file being opened successfully.
Last edited on
Okay, I implemented a check in the second program, but no error message comes up - I just get a blank line.

And what do you mean by "using the same working directory"? The code that I posted has all the "include" lines that are in the program - I've shown everything.

This is my first time ever using files in my life, so I'm sure I'm missing something basic.
Well, I added this to the second program:
1
2
3
4
5
        if  (!ifh.is_open())
        {
        	cout << "file is not open" << endl;
        	return 1;
        }

I get one of two results. If the file is not opened, the "not open" message appears.
Otherwise I get the first word of the first line displayed, "Steven".

My original guess was that the file "Student.dat" was created in one directory (or folder), but the second program was looking for it in a different directory.

Last edited on
Tip: Specify the complete path of the file in both programs.
For example /usr/home/INeedAHero/devel/data/Student.dat
Topic archived. No new replies allowed.