C++fstream读写文件问题?

bcypxl 2014-01-03 06:59:15
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
fstream file("a.txt",ios::out|ios::in|ios::trunc);
file << "Data of test!" << endl;

string str;
file >> str;

cout << "str=" << str << endl;
return 0;
}

我查看了文件中写入的数据正确,但是为什么读出的数据是空呢?也就是读不出数据,这样用不对吗?
...全文
181 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sleeplacker 2014-01-05
  • 打赏
  • 举报
回复
你的file是一个流文件,你执行了file << "Data of test" << endl; 后file就空了,所以你不能从中读数据 你应该重新创建一个流文件来读
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
	fstream file("a.txt", ios::out | ios::in | ios::trunc);
	file << "Data of test!" << endl;
	fstream read("a.txt");

	string str;
	read >> str;

	cout << "str=" << str << endl;
	return 0;
}
qq120848369 2014-01-05
  • 打赏
  • 举报
回复
读写之间一定要seek/rewind一下哈,标准IO库是有缓存的,文件的实际偏移量和标准库tell的偏移量是可能不一致的,必须要做一次seek。
  • 打赏
  • 举报
回复
告诉楼主问题出现的本质, 你打开了一个文件,无论你是读还是写,只要你不关闭文件之前,系统都会记录你上次读/写 所存在的光标位置。。 所以 我们可以 seek(0);也可以 file.close();重新定位光标。。
lm_whales 2014-01-04
  • 打赏
  • 举报
回复
ios::trunc
zybjtu 2014-01-03
  • 打赏
  • 举报
回复
#include<iostream> #include<fstream> #include<string> using namespace std; int main() { fstream file("a.txt",ios::out|ios::in|ios::trunc); file << "Data of test!" << endl; string str; file.seekg(0); file >> str; cout << "str=" << str << endl; return 0; } 看看这个http://www.cppblog.com/saga/archive/2007/06/19/26652.html

64,670

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧