在常用的三种流中处理文件的分别是:
iftream,ofstream,fstream;
ifstream:表示可以读取的文件流
ofstream:表示可以写入的文件输出流
fstream:表示可以进行读写操作的文件流
1、如何读取一个文件?
在c++中读取文件要使用iostream头文件,具体实现:
(1)必须包含头文件iostream
(2)头文件iostream定义可一个用于处理输入的iostraem类
(3)头文件中iostream声明了一个名为cin的istream变量
(4)必须指明命名空间std;
可以结合使用cin和操作符<<进行读取文件的各种数据类型,黑可以使用cin和get()读取一个字符。
使用cin和getline()读取一行字符。
<span style="font-size:18px;">#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void main()
{
char ch;
fstream openfile("F:\\a.txt0", ios::out);//可以进行读写文件流
while (openfile.eof())
{
cout << "fileis not open" << endl;
exit(1);
}
while (openfile.eof())//判断是否到了结尾
{
openfile.get(ch);
cout << ch;
}
openfile.close();
}</span>
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void main()
{
ofstream oftest;
char filename[] = "E:\\a.txt";//进行写入操作。吧数据写到文件中
oftest.open(filename, ostream::app);
oftest << a();
oftest.close();
}
int a()
{
return 0;
}