vlio20
vlio20

Reputation: 9295

Error reading txt file c++

I have this code that suppose to read a txt file. But for some reason i am always getting *File not found that means that fileIn.fail() failed...

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


using namespace std;

int main ()
{
    string fileName;
    ifstream fileIn;
    bool x;

    cout << "enter file name \n";
    cin  >> fileName;

    fileIn.open(fileName);

    if(fileIn.fail())
    {
        cerr << "* File not found";
        return true;
    }

the file located in the same folder as my main.cpp file and named input.txt. I have tried to set the fileName hard coded but this also didn't work. What is wrong with my code?

here is the project:

enter image description here

Upvotes: 0

Views: 1744

Answers (3)

Elvis Dukaj
Elvis Dukaj

Reputation: 7368

Absoulut path will always works. But I hate full path I prefer relative path for a simple reason: code is more portable. If you run your program with input.txt in the same path of executable it will work. But when you use an IDE you must set the current directory in the IDE settings.

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25705

Here is a checklist:

  1. Do you have permissions to read/access the file?
  2. Are you the owner of the file?(Linux)
  3. Are you giving the correct path, relative or absolute from the executable?

If the answer to any of these is a no, then that is where the problem lies, not just "file not found" error.

--EDIT--

@VladIoffe the executable I see there, is qustion2 and the relative path you have to give is ../input.txt and not input.txt

Upvotes: 1

Maluvel
Maluvel

Reputation: 455

You should use absolute path to the fileName.

Upvotes: 0

Related Questions