天天看点

文件读写(二)                                          文件读写之c++

目录

                                          文件读写之c++

流读写

字符读写

批量读写

行读取 

                                          文件读写之c++

文件读写(二)                                          文件读写之c++

流读写

//文件读取
	ifstream inRead;
	inRead.open(strFile1, ios::in);
	if (!inRead.is_open())
		return 0;

	char strBuf[256] = { 0 };
	int iNum = 0;
	while (!inRead.eof())
	{
		//一行一行读取数字
		inRead >> iNum;
	}
	/*while (!inRead.eof())
	{
		//一行一行读取字符串
		inRead >> strBuf;
	}*/
	inRead.close();
           
//流写入
	ofstream outWrite;
	outWrite.open(strFile1, ios::app);
	if (!outWrite.is_open())
		return 0;
	outWrite << "welcome to 2019" << endl;
	outWrite << 2019 << endl;
	outWrite.close();
           

字符读写

//字符读取
	ifstream inRead;
	inRead.open(strFile1, ios::in);
	if (!inRead.is_open())
		return 0;
	char getChar;
	inRead.get(getChar);
	cout << getChar;
	inRead.close();
           
//字符写入
	ofstream outWrite;
	outWrite.open(strFile1, ios::app);
	if (!outWrite.is_open())
		return 0;
	char putChar='a';
	outWrite.put(putChar);
	outWrite.close();
           

批量读写

//批量读取
	ifstream inRead;
	inRead.open(strFile1, ios::in);
	if (!inRead.is_open())
		return 0;
	char getBuf[256] = { 0 };
	//读取sizeof(getBuf)个字节到getBuf中
	inRead.read(getBuf, sizeof(getBuf));
	inRead.close();
           
//批量写入
	ofstream outWrite;
	outWrite.open(strFile1, ios::app);
	if (!outWrite.is_open())
		return 0;
	char putBuf[256] = {"welcome to 2019"};
	//批次写入文件,一次性写入sizeof(putBuf)个字节到文件中
	outWrite.write(putBuf,sizeof(putBuf));
	outWrite.close();
           

行读取 

//行读取
	ifstream inRead;
	inRead.open(strFile1, ios::in);
	if (!inRead.is_open())
		return 0;
	char strBuf[256] = { 0 };
	inRead.getline(strBuf, sizeof(strBuf));
	/*
		while (!inRead.eof())
		{
			//循环一行一行读取
		}
	*/
	inRead.close();
           
//行写入
	ofstream outWrite;
	outWrite.open(strFile1, ios::app);
	if (!outWrite.is_open())
		return 0;
	char strBuf[256] = { 0 };
	outWrite << "hello world" << "\n";

	outWrite.close();
           

继续阅读