提示:本文章为C++基础知识点回顾,有需要的可酌情阅读
前言
程序在运行时存储的数据都是临时数据,是不能永久保存的。程序一结束,数据就会被销毁。所以,为了实现数据的保存永久性,就需要用到文件。
在C++中,文件分为两种,一是文本文件,二是二进制文件。
一、C++文件的基本操作
在c++中,如果需要使用到文件操作,
1.首先需要引入头文件:#include <fstream>
2.声明文件对象:即以什么样的文件流来操作文件。在C++中,有以下的文件流
A.以读的方式打开文件: ifstream
B.以写的方式打开文件: ofstream
C.以读写的方式打开文件: fstream
3.打开文件:
当声明文件对象后,就可以打开文件:
ofstream ofs;
ofs.open("test.txt",ios::out);
open(“文件名称(可以写路径名称)”,打开方式)。具体也是认为比较常用的打开方式如下:
打开方式 | 备注 |
---|---|
ios::in | 以读的方式打开 只读 |
ios::out | 以写的方式打开 只写 |
ios::binary | 以二进制的方式 |
ios::truct | 覆盖原文件,重新写文件 |
4.读或者写具体内容
5.关闭文件close()。
二、写文件(文本文件)
1.代码如下
代码如下(示例):
#include <stdio.h>
using namespace std;
#include <fstream>
void test()
{
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "姓名:天天,年龄:18" << endl;
ofs << "姓名:嘻嘻,年龄:16" << endl;
ofs.close();
}
int main()
{
test();
system("pasue");
return 0;
}
结果如下:
2.读文件(文本文件)
代码如下(示例):
#include <stdio.h>
using namespace std;
#include <fstream>
#include <iostream>
void test()
{
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
//读的方式
char buf[1024] = {0};
while (ifs.getline(buf, sizeof(buf)))
{
cout << buf << endl;
}
//同时提供第二种方式读文本文件 需要注意的是 请引入头文件 #include <string>
//string str;
//while (getline(ifs, str))
//{
// cout << str << endl;
//}
ifs.close();
}
int main()
{
test();
system("pasue");
return 0;
}
结果如下:
总结
以上就是文本文件的基本操作,明天继续进行二进制文件的读写!!!