1、ifstream :分条读出txt文件中的内容
2、ofstream:(人为)先创建空的txt文件,在exe状态下手动输入内容,则会在txt文本中显示
3、把文件 c:\test.txt 复制到文件 c:\testnew.txt 中
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch;
ifstream f1("c:\\test.txt");
if (!f1)
{
cout << "Cannot open 'test.txt' for input." ;
return 0;
}
ofstream f2("c:\\testnew.txt");
if (!f2)
{
cout << "Cannot open 'testnew.txt' for output." ;
return 0;
}
while (f1.get(ch))
{
f2.put(ch);
}
f1.close();
f2.close();
cout << "It is over!\n";
return 0;
}
4、建立一个包含学生学号、姓名、成绩的文本文件
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char fileName[30], name[30];
int number, score;
ofstream outstuf;
cout << "Please input the name of students file:\n";
cin >> fileName;
outstuf.open(fileName, ios::out);
if (!outstuf)
{
cout << "File could not be open." << endl;
return 0;
}
outstuf << "学生成绩文件\n";
cout << "Input the number, name, and score: (Enter Ctrl-D to end input)\n? ";
while (cin >> number >> name >> score)
{
outstuf << number << ' ' << name << ' ' << score << '\n';
cout << "? ";
if (outstuf.fail())
{
cout << "Error writing to file." << endl;
return 1;
}
}
outstuf.close();
return 0;
}
5、读文本文件。在屏幕显示学生记录,以及最高分数、最低分数和平均分数
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char name[30], s[80];
int number, score, n = 0, max, min, total = 0;
double ave;
ifstream instuf("c:\\students.txt", ios::in);
if (!instuf)
{
cout << "File could not be open." << endl;
return 1;
}
instuf.getline(s, 80);
while (instuf >> number >> name >> score)
{
cout << number << '\t' << name << '\t' << score << '\n';
if (n == 0)
{
max = min = score;
}
else
{
if (score > max) max = score;
else if (score < min) min = score;
}
total += score;
n++;
}
ave = static_cast<double>(total) / n;
cout << "maximal is : " << max << endl << "minimal is : " << min << endl << "average is : " << ave << endl;
instuf.close();
return 0;
}
6、
文件读写
#include <iostream>
#include <fstream> // 包含头文件
using namespace std;
int main()
{
ofstream fout; // 建立流对象
fout.open("C:\\test.txt"); // 建立联系(open)
if (!fout.is_open()) //检验
{
cout << "Cannot open output file\n";
return 1;
}
fout << 10 << " " << 123.456 << " " << "This is a text file.\n"; //读写
fout.close(); //关闭
return 0;
}