Search code examples
c++visual-studio-2012ifstream

Can't get a simple ifstream to work in Visual Studio Express


I am trying to learn C++ and am on the file input/output section. I've hit a brick wall because my test application just plainly isn't working in Visual Studio Express 2012. Here is my code:

// ConsoleApp03.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    ifstream file_reader;
    file_reader.open("C:\temp.txt");

    // Test to see if the file was opened
    if (!file_reader.is_open() ) {
        cout << "Could not open file!" << endl;
        return 255;
    }
    string line;
    // Read the entire file and display it to the user;
    while (getline(file_reader,line)) {
        cout << line << endl;
    }

    // Close the file
    file_reader.close();
    return 0;
}

Every time I run this, I get "Could not open file!". I have verified that the file being opened does exist, and I have sufficient permission to read. I have tried other text files, including in other different locations like my documents folder, but the result is always the same. My text file is very simple and only contains two lines of text. I am abel to open this file in Notepad++, and the file has no special attributes (system, Read only, etc). I have even tried converting the file to/from ANSI and UTF-8 with no luck.

I have looked at other problems similar to what I have here, but these don't seem to be applicable to me (e.g.: ifstream::open not working in Visual Studio debug mode and ifstream failing to open)

Just to show how simple the text file is, here is me typing it from the command prompt:

 C:\>type C:\temp.txt
 Hi
 There

Solution

  • This may or may not fix your problem, but \ followed by char is an escape sequence. So your file path is actually invalid. Try

    file_reader.open("C:\\temp.txt");
    

    The \t actually means tab. See here.