Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中读取文件+;_C++ - Fatal编程技术网

C++ 在C+中读取文件+;

C++ 在C+中读取文件+;,c++,C++,我无法理解为什么我的代码无法打开和读取文件。我错过了什么 #include <iostream> #include <fstream> #include <string> using namespace std; int main (int argc, char * const argv[]) { string line; ifstream myfile ("input_file_1.txt"); if (myfile.is_ope

我无法理解为什么我的代码无法打开和读取文件。我错过了什么

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

int main (int argc, char * const argv[]) 
{
    string line;
    ifstream myfile ("input_file_1.txt");
    if (myfile.is_open())
    {
        while (!myfile.eof())
        {
            getline (myfile,line);
            cout << line << endl;
        }
    }
    else
    {
        cout << "Was unable to open the file" << endl;
    }

    return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(int argc,char*const argv[]
{
弦线;
ifstream myfile(“input_file_1.txt”);
如果(myfile.is_open())
{
而(!myfile.eof())
{
getline(myfile,line);
cout
  • 尝试使用文件的完整路径
  • 查找文件的默认位置是可执行文件所在的位置,而不是源文件所在的位置

从代码(包括cpp)创建的二进制文件在与代码不同的地方执行,可能是一个“bin”文件夹。您可以将该文件与可执行文件放在同一文件夹中。

如何以及在何处执行程序?从IDE? 你能从你的文本文件所在的目录下运行这个程序吗。
另一种可能是使用文件的绝对路径。

如果未指定路径,库将尝试从当前目录加载文件。您需要确保文件所在的位置

此外,如果文件是由其他程序以独占方式打开的,则可能无法打开该文件。请确保该文件未在其他程序(如编辑器)中打开。

其他问题: 明确测试EOF通常是错误的。
最后一次有效读取(此处为getline())最多读取EOF,但不超过EOF。然后打印该行,然后重新启动循环。EOF()的这些测试不会失败(因为它没有读取EOF)。然后进入循环体并尝试读取下一行(使用getline()),这会失败,因为还有0个字节要读取(从而使line的值处于未定义状态)。然后打印line(未定义的值)和换行符

    while (!myfile.eof())
    {
        getline (myfile,line);
        cout << line << endl;
    }
while(!myfile.eof())
{
getline(myfile,line);

是的,我的输入文件需要使用一个绝对路径或在我的可执行文件的位置。默认的“查找位置”在本例中,是当前工作目录,而不是可执行文件所在的目录。可执行文件不需要从其所在的目录执行。确实,许多IDE使用可执行文件所在的目录作为当前工作目录,但这是IDE的一个工件。您的第二个项目符号表示程序作为-is将始终在可执行文件的目录中查找文本文件,这是不正确的。我将重点关注当前工作目录。IDE行为是一个正交问题。该文件不必位于可执行文件所在的目录中。在本例中,该文件只需位于当前工作目录中,可能是,也可能不是可执行文件的位置。例如,如果文本文件位于
/tmp/dirA
中,可执行文件位于
/tmp/dirB
中,则可以执行
cd/tmp/dirA;/tmp/dirB/u可执行文件
,并且可执行文件应该能够找到它(在这种特定情况下)。
    while (getline (myfile,line))
    {
        cout << line << endl;
    }