【C++】代码实现:从文件中读取:字符、整型数据、浮点型数据

一、代码说明:

  • 读取字符:char* ReadChar(ifstream& in)
  • 读取整数:void read_integer(ifstream& in, int& value)
  • 读取浮点数:void read_double(ifstream& in, double& value)

特别要注意:

       在读取文件时,对文件末尾的判断(如果已到文件末尾还去读取数据,操作系统将会挂起无响应)。

二、实现代码:

  • 读取字符函数:
char* ReadChar(ifstream& in)
{
	char c_size[1];
	char *buffer;
	int size = 0;

	c_size[0] = 0;
	in.read(c_size, 1);
	size = int(c_size[0]);

	buffer = new char[size + 1];
	for (int i = 0; i < size; i++)
	{
		buffer[i] = '\0';
	}

	in.read(buffer, size);
	buffer[size + 1] = '\0';

	return buffer;
}
  • 读取整数函数:
void read_integer(ifstream& in, int& value) 
{
	in.read(reinterpret_cast<char*>(&value), sizeof(int));
}
  • 读取浮点数函数:
void read_double(ifstream& in, double& value)
{
	in.read(reinterpret_cast<char*>(&value), sizeof(double));
}
  • 实际应用示例:
extern "C" __declspec(dllexport) int CheckDataFile(const char* file_name, double* output, long &size_output)
{
	long i(0);
	double num(0.0);
	list<double> dataList;

	try
	{
		ifstream f(file_name, ios::in | ios::binary);
		if (!f) return 1;		        //检查文件是否存在

		f.seekg(0, ios::end);
		streampos fp = f.tellg();               // 取得读取位置(从第1个字节读取)

		f.seekg(0, ios::beg);
		string MachineID = ReadChar(f);		//读取字符数据
		string FileDateTime = ReadChar(f);	//读取字符数据
		int EncryptMonth = 0;
		read_integer(f, EncryptMonth);		//读取整数
		--EncryptMonth;

		streampos p = f.tellg();                //取得读取位置,用于接下来的连续读取
		num = 0.0;
		while (!f.eof())
		{
			p = fp - f.tellg();
			if (p < 8) break;

			read_double(f, num);		  //读取浮点数
			dataList.push_back(num);

			if ((i % (10 * EncryptMonth)) == 0)
			{
				f.seekg(ios::cur, 1);
			}

			++i;
		}
		f.close();
	}
	catch (const std::exception&)
	{
		return 2;	//读取文件出错
	}
    
    ......


	size_output = dataList.size();

	return 0;
}

猜你喜欢

转载自blog.csdn.net/kingkee/article/details/94433351
今日推荐