user3822749 user3822749 - 25 days ago 11
C++ Question

How to open input file, C++ on visual studio community 2015?

Does anyone know why the file isn't opening? I also tried just putting "infile.txt" and placing it in the folder of the program and also the debug folder but the ways I used to check for open error both triggered meaning that it could not open. I know I can hard code the location but I don't want to.

I heard you should do

stringobj.c_str()
but I don't know if that's accurate?

#include "stdafx.h"

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

int main()
{
ifstream infile;
ofstream outfile;

string fileloc = "infile.txt";

infile.open(fileloc);


if (!infile)
{
cout << "open fail 1" << endl;
}

bool fail = infile.fail();
if (fail)
{
cout << "open fail 2";
}

return 0;
}

Answer

Note that the directory structure (at least for VS2013) is

<base>
   - Solution Directory
     - Debug
     - Release
     - Project Directory
       - Debug
       - Release

The program by default runs in the project directory (even though it is built to the solution/debug directory).

If you accepted the default naming convention when starting your project, you should be putting your file in the "Projects\ConsoleApplication1\ConsoleApplication1" directory, not "Projects\ConsoleApplication1"

Comments