没有这样的文件或目录,在fstream c ++中被杀死

时间:2013-07-19 04:04:40

标签: c++

我是C ++的新手。

我试图使用fstream读取文件。

这是代码,

我把文件放在a.out目录下但仍然无法读取,我的错误在哪里?

#include<iostream>
#include<fstream>

int main()
{
   std::ifstream myfile("my.txt");
   int a, b;
   while(myfile>>a>>b)
   std::cout<<a<<b;

   return 0;
}

2 个答案:

答案 0 :(得分:2)

尝试:

#include <iostream>
#include <fstream>
#include <unistd.h>

int main()
{
   char* name = get_current_dir_name();
   std::cout << "Current Working Dir: " << name << "\n";
   free(name);

   std::ifstream myfile("my.txt");
   if (!myfile))
   {
       std::cout << "Failed to open file\n";
       exit(1);
   }
   int a, b;
   while(myfile>>a>>b)
   {
       std::cout<<a<<b;
   } 
   return 0;
}

答案 1 :(得分:1)

确保该文件位于.exe的当前目录中。这通常与.exe位于硬盘上的目录相同。

如果您不知道当前目录是什么,我建议您使用完整路径。