I'm missing something obvious here I think

I'm trying to check for the existence of a file, and I hear this is possible with ifstream's .good property. Not even managing to get that far. Forgive me on this, I'm new to C++

Created a new VS console application.

I then added the relevant includes:

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

After that, I tried an example I found on the web:

std::ifstream my_file("file.txt");

Adding this to my main. Rather than using namespace std; I decided to just reference it fully here as this is the only time I will use it.

Seems OK, but at compile time:

1>------ Build started: Project: TestingC++, Configuration: Debug Win32 ------
1>  TestingC++.cpp
1>c:\users\john\documents\code\c++\testingc++\testingc++\testingc++.cpp(3): warning C4627: '#include <iostream>': skipped when looking for precompiled header use
1>          Add directive to 'stdafx.h' or rebuild precompiled header
1>c:\users\john\documents\code\c++\testingc++\testingc++\testingc++.cpp(4): warning C4627: '#include <fstream>': skipped when looking for precompiled header use
1>          Add directive to 'stdafx.h' or rebuild precompiled header
1>c:\users\john\documents\code\c++\testingc++\testingc++\testingc++.cpp(10): error C2039: 'ifstream' : is not a member of 'std'
1>c:\users\john\documents\code\c++\testingc++\testingc++\testingc++.cpp(10): error C2065: 'ifstream' : undeclared identifier
1>c:\users\john\documents\code\c++\testingc++\testingc++\testingc++.cpp(10): error C2146: syntax error : missing ';' before identifier 'my_file'
1>c:\users\john\documents\code\c++\testingc++\testingc++\testingc++.cpp(10): error C3861: 'my_file': identifier not found
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I've looked up a few examples, but this is definitely a valid solution it would seem, and I don't want to use boost for this, so why does this throw an error?

Ideally, after a valid declaration of an ifstream, I'd like to use the .good() method to evaluate if the file exists.


4 Years
Discussion Span
Last Post by mLearning

The first include statement must be "stdafx.h" when using pre-compiled header

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

Edited by rstralberg


You need to put #include "stdafx.h" at first and then include all other header files.

Where to find precompiled headers: if you will go to properties of your project -> Under "Configuration Properties" -> "C/C++" -> Precompiled Headers. You can see the stdafx.h specified over there.

Edited by mLearning: mistake in typing

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.