Question:
C++ question, ifstream does not read file?
Dr.Bk
2010-10-02 21:19:00 UTC
I have Visual C++ 2010 Express Edition on Windows XP.

My problem is:

ifstream does not read my txt file and main always returns 1.

This is my code:

#include
#include
#include
#include

using namespace std;

int main()
{
ifstream infile("text1.txt");

if (!infile)
{
return 1; //if cannot find file, all of the time


char response;
cin >> response;

return 0;
}

It does not recognize my txt file "text1.txt", which is a single word "cool".

It is in C:\Documents and Settings\My Documents\Visual Studio 2010\Projects\frequency\frequency\text1.txt

please assist if you can
Five answers:
The Phlebob
2010-10-03 18:06:26 UTC
Along the same lines, you give the filename, but no path. How's C++ supposed to know where to look for the text1.txt file? If you provided a full pathname in the ifstream() call, like this:



ifstream infile("C:\Documents and Settings\My Documents\Visual Studio 2010\Projects\frequency\frequency\text1.txt");



it would probably work.



Hope that helps.
husoski
2010-10-02 21:41:35 UTC
Normally, this means that the file is not in the current working directory. By default, Visual Studio sets the current working directory to the location of the .exe file. That's either the Debug or Release subdirectory of your project directory, depending on the build type. Assuming you're using the debug configuration, try copying the text file to the Debug subdirectory.



Or, you can set the debug working directory from Project Properties under Debugging. You could try putting the location of the text file there. Set the configuration drop-down to "All configurations", click on Debugging in the project property tree, and use the drop-down on "Working directory" to get to to pick the location of the text file.
Cheryl
2016-04-21 05:32:43 UTC
There is nothing wrong with your program. It has no syntax or style errors and It works for me, when I place the text1.txt file in the directory from which this program is executed. In your case, I am betting you're executing the program from a different folder. Try using full path (C:\\Documents and Settings\\My ...) instead of just "test1.txt".
mcduffey
2016-10-07 16:57:58 UTC
Ifstream Read
oops
2010-10-02 21:29:02 UTC
How is this compiling? Where is your other brace?


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...