harryprotist
harryprotist

Reputation: 45

C++ ifstream will not open any files

Whenever I try to open a file with ifstream, it compiles fine, but will not open the file. The file in this example doesn't exist, but ifstream *s*should*s* create the file for me.

i have some example code that i think should work, but does not open or create the file "foo.txt". Is there something that i'm missing, or is my IDE just messed up? i'm using visual studio 2008 VC++ , btw

thanks

here's the code:

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
    ifstream in;
    string hold;
    in.open("foo.txt",ios::in);
    if(!in){
        cerr << "Couldn't open file!" << endl;
    }
    in >> hold;
    cout << hold << endl;
    system("pause");
    return 0;
}

Upvotes: 0

Views: 4769

Answers (2)

Alex Brooks
Alex Brooks

Reputation: 1151

The problem is you are using an in stream instead of an out stream, as Adam Liss mentioned(ios::out rather than ios::in). You also need to make sure you close the file before return 0; to make sure everything from the buffer is actually written to the file.

Upvotes: 1

Adam Liss
Adam Liss

Reputation: 48330

The open function will not create files in ios::in mode; you need to use ios::out.

Upvotes: 1

Related Questions