无法打开输入文件 [英] Cannot open input file

查看:111
本文介绍了无法打开输入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基本程序,它将从文本文件中读取整数列表,并将文件中最小的整数和最大整数输出到屏幕。
我确保文本文件与源代码文件在同一个文件夹中,文件的名称与代码中的名称相同。程序无法打开文件,无论什么。如何解决这个问题?

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?

这是我的程序:

 #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;
}


推荐答案

C:\ SomeDirectory\infile.txt,它将是绝对路径。这与被称为相对路径的infile.txt相反。这提出了一个问题,它在哪里相对?。它相对于当前工作目录或CWD。通常,CWD设置为可执行文件所在的位置,但它不必是!实际上,如果将文件拖放到可执行文件中,CWD将是您拖动文件的位置。或者如果从Visual Studio运行并从IDE内部启动代码(通过点击按钮或使用F5),CWD不会是可执行文件的位置。

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.

简短的答案是你一般都想使用绝对路径。有些情况下,相对路径是有意义的,但是你真的必须理解你的程序是如何被使用的,CWD在哪里是有用的。对于你的情况,我只是坚持一个绝对的路径。

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.

这篇关于无法打开输入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆