0

My code is supposed to open a file and work with the data that it reads in. My code looks like this:

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
int main()
{
  ifstream input_file;
  input_file.open("practice.txt");

  if (input_file.fail())
  {
    cout << "Attempt to open file failed." << endl;
  }

  else

It always returns "attempt to open file failed". I am definitely using the correct file name, so what are some reasons that the file isn't opening?

How do I solve this issue?

EDIT: spoke to another girl in my class with a Mac and her code works perfectly when not run on Mac but won't open the file when she runs it on her computer so I think it's a problem with my compiler. Thanks for the help!!

Kate
  • 1
  • 2
  • 2
    The most likely reason is that the directory from where the program runs and the directory where the file is are different. Use absolute path to the file to make sure permissions are not responsible for the failure to open the file. – R Sahu Mar 22 '19 at 04:43
  • Search term: "Working Directory" – user4581301 Mar 22 '19 at 04:46
  • @RSahu how would I do that? I'm using Code::Blocks as my compiler and it creates a folder in the documents on my computer, so I put the file in the folder that it created for this project. Where is the best place to put it? – Kate Mar 22 '19 at 05:01
  • Assuming you are using Windows, move the input file, practice.txt, to "C:\". Change the line to open the file to `input_file.open("C:\\practice.txt")`. Please note the use two backward slashes - "\\". Don't change it to one. – R Sahu Mar 22 '19 at 05:06
  • I'm using a Mac. Are you familiar with any equivalents for that? – Kate Mar 22 '19 at 05:09
  • You should look at this post for getting more detail on why the fail read fails: https://stackoverflow.com/questions/17337602/how-to-get-error-message-when-ifstream-open-fails – Evan Mar 22 '19 at 15:35

0 Answers0