文本文件操作:
C++中文件类型有两种:文本文件和二进制文件
文本文件是由字符的ASCII码值的形式存储;二进制文件是由二进制数据形式存储。
文件输出操作流程:
1.包含头文件<fstream>
2.对象的建构:
文件操作的类有三种:
ofstream--只写、ifstream--只读、fstream--可读可写。我们随后根据需要创建一个对象:例如输出流对象ofs的创建 ofstream ofs;
3.打开文件:
这里打开文件的操作是使用函数open,具体语法是:对象名+open+(”文件路径“ , " 打开方式");
文件路径可以是相对路径也可以是绝对路径,文件路径后面记得加上文件的类型,如txt类型。
打开方式 | 对应操作 |
ios::in | 为读文件而打开 |
ios::out | 为写文件而打开 |
ios::ate | 文件尾为初始位置 |
ios::app | 追加内容 |
ios::trunc | 重写文件 |
ios::binary | 二进制形式读写 |
不同的打开方式配合 | 操作符使用。
4.输出内容:
对象名+ << +内容
5.关闭文件:
类名+fclose();
示例:
#include<iostream>
using namespace std;
#include<fstream>
void test()
{
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "ABCDE" << endl;
ofs << "FGH" << endl;
ofs.close();
}
int main()
{
test();
return 0;
}
文件输入操作流程:
前面几部与输出大同小异,主要是总结读取文件的4种方式:
第一种:使用一个字符串类型来接收,使用getline将每一行都读入到字符串中
string buf;
while ( getline(ifs,buf))
{
cout << buf << endl;
}
第二种:使用一个字符数组来接收,使用ifs里面的getline函数接收
char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf)))
{
cout << buf << endl;
}
第三种:使用一个字符数组接收,直接用cin>>buf来接收
char buf[1024] = { 0 };
while ( ifs>>buf )
{
cout << buf << endl;
}
第四种:使用一个字符变量来接受,用get函数每次接收一个字符
char c;
while ((c = ifs.get()) != EOF)
{
cout << c;
}
二进制类型文件读写流程:
二进制文件的写与文本文件读写类似,不同的地方是二进制文件的写操作是使用一个输出流下的write函数。
具体操作是:对象名.write+((const char *)(指向内容的指针) , sizeof(数据大小));
而读入的操作是利用函数read,具体操作是:
对象名.read+((char*)(指向数据内容指针) , sizeof(数据大小) );
void test()
{
char str[50] = "梁";
ofstream ofs;
ofs.open("test.txt", ios::out | ios::binary);
ofs.write((const char*)str, sizeof(str));
}
void test2()
{
char buf[50] = { 0 };
ifstream ifs;
ifs.open("test.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "Fail!" << endl;
return;
}
ifs.read((char*)buf, sizeof(char) * 50);
cout << buf << endl;
ifs.close();
}