Joissa.R
Joissa.R

Reputation: 111

getline() not opening text file

Hi I am currently using CodeBlocks 13.12 on OSX.

I am trying to open the following .txt file

line 1
line 2
line 3

My code is just:

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

using namespace std;

int main()
{
    cout<<'\n';
    std::string line;
    ifstream myfile("textex.txt");
    if(myfile.is_open())
        cout << "File is open";
    else
        cout << "File not open";

    cout<<'\n';
    return 0;
}

I have also included the file in the project folder and have tried linking it and compiling it.

When I run the code, it displays"File not open" and I'm not sure why? I'm new to c++, can someone please explain why this isn't working?

Upvotes: 1

Views: 297

Answers (4)

Arda Kara
Arda Kara

Reputation: 521

When you run your program from Code::Blocks it runs on project folder so your text file must be in your project folder, otherwise text file must be in the folder where your executable is.

Upvotes: 0

Anthony Kong
Anthony Kong

Reputation: 40814

Instead of

    ifstream myfile("textex.txt");

Try

    ifstream myfile;
    myfile.open("/Users/name/Code/textex.txt"); // Use the full path

Upvotes: 0

hussamash
hussamash

Reputation: 43

Try typing the full path of the file instead of just the file name. Tell me what happens then.

On another note but unrelated, since you are using the "using namespace" directive, you may as well omit std:: from string just like you did with cin and cout. It is not a big deal, just the look of the code.

Upvotes: 0

Don Reba
Don Reba

Reputation: 14051

Possibly because the project folder is not set as the working directory. Try specifying the full path.

Upvotes: 1

Related Questions