Daniel Pantigoso
Daniel Pantigoso

Reputation: 35

Failure to open fstream C++ file even though it's in same location as .cpp

I'm currently doing some schoolwork and I can't get this simple piece of code (I've extracted it) to work. I just need it to open the file so I can read and write to it. The file (Sedes.txt) is in the same location as both the .cpp and the .exe, in the current working directory. Even adding the path with C:\ or C:\ or C:// or C:/ doesn't work. I'm using DEV C++ with Compiler Code Generation option -std ISO C++11

I've also confirmed using this link with the solution code to corroborate the directory. It outputs in the same folder.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

fstream aSedes("Sedes.txt");

int main(){
   string txtWrite = "";
   string txtRead = "";

   aSedes.open("Sedes.txt", ios_base::in | ios_base::out);
   if(aSedes.fail()){
       cout << "!---ERROR: Opening file ln 446---!";
   } else {
       cout << "Sedes.txt opened successfully." << endl;
       cout << "Text in file: " << endl;
       while(aSedes.good()){
           getline(aSedes, txtRead);
           cout << txtRead << "\n";
       }
   }
   aSedes.close();

   return 0;
}

I'm honestly, completley lost. I've tried switching it out everywhere to no avail.

Upvotes: 1

Views: 647

Answers (1)

john
john

Reputation: 88027

You are opening the file twice, once with the constructor and once with open

fstream aSedes("Sedes.txt"); // opened here

int main(){
   string txtWrite = "";
   string txtRead = "";

   aSedes.open("Sedes.txt", ios_base::in | ios_base::out); // and here again
   if(aSedes.fail()){

Try this instead

int main(){
   string txtWrite = "";
   string txtRead = "";

   fstream aSedes("Sedes.txt", ios_base::in | ios_base::out);
   if(!aSedes.is_open()){

You should probably prefer is_open for checking that a file is open. And you should probably use a local variable for the stream. But if you want a global variable then this should also work

fstream aSedes;

int main(){
   string txtWrite = "";
   string txtRead = "";

   aSedes.open("Sedes.txt", ios_base::in | ios_base::out);
   if(!aSedes.is_open()){

Upvotes: 1

Related Questions