-1

I am trying to get my program to read a file and use the file as input information. I put the file in the same directory as my program, but still nothing.

Here is my code:

int main()
{
    ifstream inFile;
    inFile.open("inData.txt");
    if (inFile.fail())            
    {
        cout << "file did not open please check it\n";
        system("pause");
        system("exit");
    }
    studentType sList[20];
    getData(inFile, sList, 20);
    calculateGrade(sList, 20);
    printResult(sList, 20);
    inFile.close();
    system("pause");
    return 0;
}
7
  • 1
    What compiler are you using? MSVS uses where the source files are as the working directory Commented Jul 28, 2018 at 2:09
  • 1
    I believe you are running the code from an IDE, such as MSVS. So an idea is to print the directory where the program is running and make sure there is a "inData.txt" file there . Take a look at stackoverflow.com/a/198099/4289700. Commented Jul 28, 2018 at 2:35
  • 2
    If your top priority is to get this working, I suggest using the complete path. Ex: inFile.open("C:\\myHome\\testFile.txt");. that is also a good practice to do in your production code.
    – Omi
    Commented Jul 28, 2018 at 7:00
  • The working directory is initialised when the process is started. It depends on how the process is started. How do you start the process? Commented Jul 28, 2018 at 7:07
  • @DavidHeffernan 'Initialized' isn't a great choice of words. It is determined by where you are when you start the process.
    – user207421
    Commented Jul 28, 2018 at 7:55

1 Answer 1

0

Compile and run this program from the same location your program is. Wherever it creates the file output.txt is your working directory:

#include <fstream>

int main(int argc, char **argv)
{
    std::ofstream myfile;
    myfile.open("output.txt");
    myfile << "output\n";
    myfile.close();
    return 0;
}

When you run your program, put your inData.txt file in that directory.

3
  • 2
    You can just pass the file name to the constructor of std::ofstream and let the destructor close the file for you.
    – eesiraed
    Commented Jul 28, 2018 at 4:04
  • I ran this, and it turns out it is the same directory where I originally placed my "inData.txt" file.
    – 5MikesOut
    Commented Jul 28, 2018 at 4:37
  • @5MikesOut did you run my program and yours from the exact same location? if so, can you add the ls output (or windows equivalent) of this directory? Commented Jul 28, 2018 at 5:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.