Search code examples
c++visual-studioifstream

ifstream::open not working in Visual Studio debug mode


I've been all over the ifstream questions here on SO and I'm still having trouble reading a simple text file. I'm working with Visual Studio 2008.

Here's my code:

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

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

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{

    ifstream infile;
    infile.open("input.txt", ifstream::in);

    if (infile.is_open())
    {
        while (infile.good())
            cout << (char) infile.get();
    }
    else
    {
        cout << "Unable to open file.";
    }
    infile.close();
    _getch();
    return 0;
}

I have confirmed that the input.txt file is in the correct "working directory" by checking the value of argv[0]. The Open method just won't work.

I'm also having trouble debugging- should I not be able to set a watch on infile.good() or infile.is_open()? I keep getting

Error: member function not present.

EDIT: Updated code listing with full code from .CPP file.

UPDATE: The file was NOT in the Current Working Directory. This is the directory where the project file is located. Moved it there and it works when debugging in VS.NET.


Solution

  • Try using the bitwise OR operator when specifying the open mode.

    infile.open ("input.txt", ios::ate | ios::in);
    

    The openmode parameter is a bitmask. ios::ate is used to open the file for appending, and ios::in is used to open the file for reading input.

    If you just want to read the file, you can probably just use:

    infile.open ("input.txt", ios::in);
    

    The default open mode for an ifstream is ios::in, so you can get rid of that altogether now. The following code is working for me using g++.

    #include <iostream>
    #include <fstream>
    #include <cstdio>
    
    using namespace std;
    
    int main(int argc, char** argv) {
        ifstream infile;
        infile.open ("input.txt");
    
        if (infile)
        {
            while (infile.good())
                cout << (char) infile.get();
        }
        else
        {
            cout << "Unable to open file.";
        }
        infile.close();
        getchar();
        return 0;
    }