Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

fstream

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;
}
like image 793
user3822749 Avatar asked Sep 18 '15 03:09

user3822749


1 Answers

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"

like image 58
The Dark Avatar answered Nov 14 '22 23:11

The Dark