Why is ifstream not opening my file?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alex T

    #1

    Why is ifstream not opening my file?

    This is my code:

    Code:
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
    	ifstream infile;
    	infile.open("text1.txt");
    
    	if (!infile.is_open())
    	{
    		return 1; //if cannot find file, all of the time
    	}
    
    	char response;
    	cin >> response;
    
    	return 0;
    }
    The program cannot open the file, and thus always returns 1;

    My text1.txt file is in C:\Documents and Settings\Alex\M y Documents\Visua l Studio 2010\Projects\f requency\freque ncy\text1.txt

    How do I make it open the file so 1 is not returned?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Your program attempts to open a file in the current directory so the most likely reason is that your program is not being run in the same directory as the directory you have placed your text1.txt file in.

    Comment

    • Alex T
      New Member
      • Oct 2010
      • 29

      #3
      I have figured out why:

      When I write
      Code:
       infile.open("text1.txt");
      I need to write the directory as so:

      "C:\\text1.txt"

      Thank you.

      Comment

      • fecalTransplant
        New Member
        • Jan 2023
        • 1

        #4
        Just to add to what Alex said 12 years ago: If you're opening the following example path as described by your operating system:

        Code:
        "D:\C++\RawDataReader\RawDataReader\data.csv"
        You would need to do the infile.open with the text as:

        Code:
        "D:\\C++\\RawDataReader\\RawDataReader\\data.csv"
        And this worked. So now I'll just be making a loop to add an extra '\' wherever there's one in the filename.

        C++ can be a little mystifying at times
        Last edited by fecalTransplant; Jan 15 '23, 01:48 AM. Reason: Label the code as code

        Comment

        Working...