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;
}
理解:
- 可以同时打开多个文件进行操作,然后统一关闭
- 文件成员函数eof()判断文件是否为空或者是否读到文件结尾,返回true时是读到文件结束符0xFF
- 可以用getline(c,999)直接读取一行的999个字符,留一个空位是为可能的结束符
928

被折叠的 条评论
为什么被折叠?



