0

So this is a simple C++ program for reading a file and displaying its contents. My directory structure is as follows

Project Directory
|
Data___
|      |
|      data.txt
|
program1.cpp

and The program:

#include <iostream>
#include <fstream>

using namespace std;

int main () {
    char char1;

    fstream data; // Because I wanna to write to this file later.
    data.open("../Data/data.txt",ios::out | ios::in);

    if (data.is_open()) {
        for (int i = 0; !data.eof(); ++i) {
            data.get(char1);
            cout << char1 << endl;
        }
        data.close();
    }

    return 0;
}

So currently my program works fine... However when I use:

data.open("Data/data.txt",ios::out | ios::in);

The program doesn't work. Why is this so? Ideally the above mentioned code piece should work since the Data folder is in the same directory as my cpp file.

data.open("../Data/data.txt",ios::out | ios::in);

By using 2 dots we are going back a directory and the Data folder isn't there.

Then why is the program working using the 2 dots?

Vedant Kashyap
  • 111
  • 1
  • 3
  • 12
  • Pathnames are interpreted relative to your current directory, not the directory containing the program. – Barmar Jan 10 '18 at 19:57
  • 1
    Where your cpp file is has nothing to do with where the search starts. The current directory of your executable is where the seach begins. – Mike Vine Jan 10 '18 at 19:57
  • Got it... turns out my executable was located in a different folder in the project directory itself... Thanks! @Barmar and Mike – Vedant Kashyap Jan 10 '18 at 19:59
  • 1
    Regarding `for (int i = 0; !data.eof(); ++i)`, give [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) a read. It can save you some future debugging. – user4581301 Jan 10 '18 at 20:08

1 Answers1

0

Looking at your directory structure, I see that both your program1.cpp and data.txt are in the same "Data" folder. Since you are already inside the Data folder, "Data/data.txt" looks for another Data folder. In UNIX ".." means the previous directory. So when you use ".." you go to "Project Directory", which contains a "Data" folder. That is why data.open("../Data/data.txt",ios::out | ios::in) is working. You can also try using the following: data.open("data.txt",ios::out | ios::in);

Nischal
  • 1
  • 1