【问题标题】:ofstream and ifstream path works writing not reading in C++ Builderofstream 和 ifstream 路径可以在 C++ Builder 中写入而不是读取
【发布时间】:2017-03-13 03:22:32
【问题描述】:

我可以使用ofstream创建如下文本文件,到指定路径:

std::string path = "c:\users\john\file.txt";
std::string str = "some text";

ofstream myfile;
myfile.open (path);
myfile << str; // write string to text file
myfile.close();    //close file

当我尝试打开/读取文件时,系统似乎打开了文件,但在此处抛出“未找到数据”异常......即使文件在那里并且包含文本。


std::string line = "";
std::string str = "";
std::string path = "c:\users\john\file.txt";

ifstream file (path);  
if (file.is_open())
{
   while ( getline (file,line) )
   {
      str = str + line;
   }

   file.close();

   if (str == "")
   {
      throw(Exception("Error: No data found..."));
   }
}

else

throw(Exception("Error: File not found..."));

这似乎只在尝试从调试文件夹以外的某个位置读取时才会发生...

如果我可以在用户目录中创建文件,为什么我不能读取它?

谁能帮忙?

更新:

我刚刚发现,如果运行写入功能并且在应用程序仍在运行的情况下立即运行读取功能,则它可以工作。但是,如果运行写入功能,则应用程序关闭并重新打开读取功能,然后如上所述失败。

【问题讨论】:

  • 不应该是std::string str="some text";吗?
  • std::string path = "c:\users\john\file.txt"; 应该是 std::string path = "c:\\users\\john\\file.txt"; 而且你永远不会检查 myfile.open (path); 在写作时是否有效。
  • 什么是getline?当您将它用于其他 stl 构造时缺少 std:: 前缀让我想知道它是 std::getline 还是自定义的东西。那里可能隐藏着一个错误。
  • @JeremiahB 我怀疑,OP 可能使用了using namespace std;
  • 是的,这是一个错字,对不起...

标签: c++ c++builder


【解决方案1】:

改为使用单个正斜杠 (/)。

对文本文件的写入操作与我们使用 cout 操作的方式相同:

// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

也可以像使用 cin 一样执行从文件中读取的操作:

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

【讨论】:

  • 这如何解决 OP 描述的问题?
  • 看到了,本质上并没有更好。
  • 刚刚发现程序在运行时正在清除文件....与读取操作无关的其他一些问题...
【解决方案2】:

您的编写代码静默失败,您应该将其更改为

std::string path = "c:\users\john\file.txt";
std::string str = "some text";

ofstream myfile;
myfile.open (path);
if(myfile.is_open()) // <<<<<<<
    myfile << str; // write string to text file
}
else {
    std::cout << "Cannot open file." << std::endl;
}
myfile.close();    //close file

您的主要问题是字符串文字中的反斜杠需要转义:

std::string path = "c:\\users\\john\\file.txt";
                   // ^      ^     ^

因此根本无法打开文件进行写入,而您没有注意到这一点,因为您的代码从未检查过它。

【讨论】:

  • 也许值得在一个关于检查myfile &lt;&lt; str是否成功的注释中折腾。
  • @user4581301 当然,如果文件无法打开,那也会失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-28
  • 2015-07-25
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 2019-10-27
相关资源
最近更新 更多