1

i am trying to open file for read/write purpose. Below code is not working ? can anyone explain me where i m doing wrong?

#include <iostream>
#include <fstream>

int main()
{
    using namespace std;
    ifstream file;
    file.open("program.txt");

    if (!file)
    {
        cout << "failure";
    }
    return 0;

}

the output of above program is "failure".
but why?
isn't it supposed to open file sucessfully?

Aayush Neupane
  • 1,066
  • 1
  • 12
  • 29
  • 1
    What if the file `program.txt` can't be found in the running process working directory? How do you run your program? What environment are you using? – Some programmer dude Feb 19 '20 at 12:37
  • @arundeepchohan I cannot see anything bad to limit the scope of a `using namespace std;`. The only general hint I saw again and again: Don't use `using namespace std;` at all (and especially not in global scope of headers). – Scheff's Cat Feb 19 '20 at 12:52
  • A file without explicit absolut path is usually located in the current working directory. Starting a binary from e.g. `bash` or `cmd.exe`, you see/know the current working directory. If you start the executable in VisualStudio, the current working directory might be the folder where the binary is stored but not the folder of the sources where you `program.txt` might be stored as well. However, the current working directory for debugging can be adjusted in the project settings of VisualStudio. (It's probably similar in other IDEs as well.) – Scheff's Cat Feb 19 '20 at 12:55
  • This doesn't address the question, but get in the habit of initializing objects with the correct value instead of default-initializing them and immediately modifying them. That is, change `ifstream file; file.open("program.txt");` to `ifstream file("program.txt");`. – Pete Becker Feb 19 '20 at 14:43

2 Answers2

0

If you are using linux / macos. try this code, it will show you the reason of failure.

#include <iostream>
#include <fstream>
#include <stdio.h>

int main()
{
    using namespace std;
    ifstream file;
    file.open("program.txt");

    if (!file)
    {
    perror("open failure");
    }
    return 0;

}

I guess the reason is "No such file or directory". Maybe you can try to switch your "current directory" to find the file.

Kirby Zhou
  • 161
  • 1
  • 10
0

I got the same issue and did some research and not find the cause. later I tried it using absolute path for the file and find it works.

file.open("program.txt");

------> should be
file.open("/absolute path/program.txt");