Cannot open input file

2020-05-09 23:30发布

问题:

I'm writing a basic program that will read a list of integers from a text file and output to the screen the smallest integer and largest integer in the file. I made sure that the text file is in the same folder as the source code file, and the name of the file is the same as what I call it in the code. The program cannot open the file, no matter what. How can I fix this?

This is my program:

 #include <iostream>
 #include <fstream>
 #include <cstdlib>
 using namespace std;

int main()
{
    ifstream inStream;

    inStream.open("infile.txt");
    if (inStream.fail())
    {
        cout<<"Input file opening failed.\n";
        system("pause");
        exit(1);
    }

    int arr[100], i = 0;

    while(!inStream.eof())
    {
        inStream>>arr[i++];
    }

    int min = arr[0];

    for (int index = 1; index <= i; index++)
    {
        if (arr[index] < min)
        {
            min = arr[index];
        }
    }

    int max = arr[0];

    for (int index = 1; index <= i; index++)
    {
        if (arr[index] > max)
        {
            max = arr[index];
        }
    }

    cout<<"The smallest number is "<<min<<endl;
    cout<<"The largest number is "<<max<<endl;

    inStream.close();

    system("pause");
    return 0;
}

回答1:

If you tried to open "C:\SomeDirectory\infile.txt" that would be an Absolute Path. This is opposed to "infile.txt" which is called a relative path. That begs the question, "where is it relative to?". It is relative to the "Current Working Directory" or CWD. Generally the CWD is set to where the executable is, but it doesn't have to be! In fact, if you drag and drop a file onto your executable, the CWD will be the location of where you dragged your file from. Or if you run from Visual Studio and launch the code from inside the IDE (by hitting the button or using F5) the CWD will not be where the executable is.

The short answer is you generally want to use absolute paths. There are definitely cases where relative paths make sense, but you really have to understand how your program is being used and where the CWD is in order for that to be useful. For your case, I would just stick to an absolute path.



标签: c++ oop file-io io