文件指针的问题

C++文件I/O

//将两个文件合并成一个文件
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	fstream myFile1("123.txt", ios::out);//用可输入输出的类定义对象
	myFile1 << "aaaaaaaaaaaaaaaaa\n";
	myFile1 << "bbbbbbbbbbbbbbbbb\n";
	myFile1.close();
	fstream myFile2("456.txt", ios::out);
	myFile2 << "ccccccccccccccccc\n";
	myFile2 << "ddddddddddddddddd\n";
	myFile2.close();

	char ch;
	string content;//先读出myFile2的内容在销毁它
	myFile2.open("456.txt", ios::in);
	while (myFile2.get(ch))
	{
		content += ch;	//把内容全加到content
	}
	myFile2.close();
	//cout << content.size() << endl;//36

	//myFile1.open("123.txt", ios::app|ios::in);
	myFile1.open("123.txt", ios::app);
	myFile1 << content;//把内容全加到myFile1
	//到这里没问题

	//注意:此时文件指针应该在字符的最末尾,此时直接执行下面注释的语句的话,
	//打印出来的将不是存入的字符,而是乱码,应该先关了文件再重开,让文件指针指在字符初始位置

	myFile1.close();
	myFile1.open("123.txt", ios::in);
	while (myFile1.get(ch))
	{
		cout << ch;
	}
	myFile1.close();

	/*while (myFile1.get(ch))
	{
		cout << ch;
	}
	myFile1.close();*/

	system("pause");
	return 0;
}

向文件输入内容后文件指针指向文件末尾,要输出文件的内容需要重新打开文件,让文件指针指在字符初始位置。

学习:
如何更好地使用string类?

例程:

#include<iostream>
#include<fstream>
using namespace std;
int main() 
{
	int i = 1;
	char c[1000];
	ifstream ifile1("123.txt");
	ifstream ifile2("456.txt");
	ofstream ofile("789.txt");
	while (!ifile1.eof()) {
		ifile1.getline(c, 999);
		ofile << c << endl;
	}
	while (!ifile2.eof()) {
		ifile2.getline(c, 999);
		ofile << c << endl;
	}
	ifile1.close();
	ifile2.close();
	ofile.close();
	return 0;
}

理解:

  1. 可以同时打开多个文件进行操作,然后统一关闭
  2. 文件成员函数eof()判断文件是否为空或者是否读到文件结尾,返回true时是读到文件结束符0xFF
  3. 可以用getline(c,999)直接读取一行的999个字符,留一个空位是为可能的结束符
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值