【发布时间】: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