C++ fstream踩坑,更新式写文件方法

C++ fstream踩坑,更新式写文件方法,第1张

先贴代码
这个是C风格写文件

		FILE* fp_enc = fopen(dec_file_path, "rb+");
		fseek(fp_enc, 0, SEEK_SET);

这个是C++风格写文件

	std::fstream outStreamFile;
	outStreamFile.open("1.txt", std::ios::in | std::ios::out | std::ios::binary);
	if (!outStreamFile.is_open())
	{
		outStreamFile.open("1.txt", std::ios::out | std::ios::binary);
	}
	if (outStreamFile.is_open())
	{
		outStreamFile.seekp(10);
		outStreamFile.write((char*)"1234567890", 10);
	}
	outStreamFile.close();

注意部分更新需要关注的点
std::ios::in | std::ios::out结合可以打开文件并SEEK写入,但是有一个问题是在于没有实际的文件的情况下不会进行文件的创建,打开失败
所以需要判断一下,如果打开失败使用 std::ios::out直接创建文件并写入

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/993419.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-21
下一篇2022-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存