user525717
user525717

Reputation: 1652

C++ fstream always fails on .txt file

my .exe and addrr.txt files are located on D:\ drive

when im trying to ready .txt file ifstream does nothing

this is my code:

 ifstream file;
        file.open("addrr.txt", fstream::in | fstream::out);
        if (file.is_open())
        {
            while (file.good())
            {
                cout << "Addrr.txt IsGood" <<endl;
                getline(file, Path);
            }

            file.close();
        }

sorry for such dumb question. im noob

Upvotes: 2

Views: 862

Answers (1)

moooeeeep
moooeeeep

Reputation: 32512

UPDATE

To make sure that the file addrr.txt can be found during runtime of the application you need to

  • specify the absolute path to the file, i.e. D:\addrr.txt, or
  • specify the relative path from the current working directory (CWD), which is C:\Program Files\Mozilla FireFox apparantly. (Which is impractical if the file is located on another partition.)

The CWD is usually the directory from which the application is run. If you'd run your application in D: it should work. (Your application may well change the CWD at runtime (e.g. by use of chdir(), or SetCurrentDirectory()). However, usually it is more appropriate to specify the absolute path to the files or to place the files in the correct relative location to the CWD.)


This compiles and runs fine for me:

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
  ifstream file;
  file.open("addrr.txt", fstream::in | fstream::out);
  if (file.is_open())
  {
    while (file.good())
    {
      string Path;
      cout << "Addrr.txt IsGood" <<endl;
      getline(file, Path);
      cout << Path << endl;
    }
    file.close();
  }
}

// output similar to:
/*
Addrr.txt IsGood
addrr.txt
Addrr.txt IsGood
addrr.txt
Addrr.txt IsGood
addrr.txt
Addrr.txt IsGood

Addrr.txt IsGood

*/


// file: addrr.txt
/*
addrr.txt
addrr.txt
addrr.txt

*/

Is your filename correct (i.e. case sensitively speaking)? Do you run your application from the path where the executable is located (s.t. the file is located in the current working directory)?

Upvotes: 2

Related Questions