std::ifstream与std::ofstream读写文件

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也会阻塞,直到所有的都写完或出现错误才返回,代码略

你可能感兴趣的:(C/C++,ifstream,ofstream)