std::ifstream与std::ofstream读写文件
  WtpFkP2ympcR 2023年11月02日 29 0


std::ifstream读取文件

unsigned char* pFileBytes = nullptr;
	unsigned int nTotalSize = 0;
	std::ifstream infile("1.dat", std::ios_base::in | std::ios_base::binary);
	if (infile.is_open())
	{
		infile.seekg(0, std::ios_base::end);
		unsigned long long nFileSize = infile.tellg();
		if (0 == nFileSize)
		{
			assert(false);
			return;
		}
		pFileBytes = new unsigned char[nFileSize];
		infile.seekg(0, std::ios_base::beg);
		memset(pFileBytes, 0, nFileSize);
		
		//1、每次读取8K
		//do
		//{
		//	infile.read((char*)(pFileBytes + nTotalSize), 8192);
		//	int nReadBytes = infile.gcount();
		//	if (nReadBytes > 0) nTotalSize += nReadBytes;
		//} while (infile.good());

		//2、一次性读取所有,read会阻塞,直到所有的都读取完或出现错误才返回
		infile.read((char*)(pFileBytes + nTotalSize), nFileSize);
		int nReadBytes = infile.gcount();
		if (nReadBytes > 0) nTotalSize += nReadBytes;



		infile.close();
	}

std::ofstream写文件

与std::ifstream差不多,write也会阻塞,直到所有的都写完或出现错误才返回,代码略


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
WtpFkP2ympcR