0
点赞
收藏
分享

微信扫一扫

c++读写文件操作

颜路在路上 2022-04-25 阅读 80
c++

程序的运行产生的数据都是临时数据,不能持久的保存,一旦程序运行结束数据就会被释放。

在C++中对文件进行操作必须包含头文件<fstream>;

对文件操作的类

  1. fstream:可读可写操作
  2. ifstream:只能读操作
  3. ofstream:只能写操作

#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ofstream ofs;//创建流对象 ->往文件里写
ofs.open("123.txt");//打开文件123.txt如果没有会自动创建,
ofs << "我们可以写入文件了!";
ofs.close();//关闭文件


return 0;
}

文件ofs.open("123.txt",打开方式)

文件的打开方式

  1. ios::in 为读文件打开方式 
  2. ios::out 为写文件打开方式
  3. ios::ate 初始位置文件尾
  4. ios::app 写文件尾追加
  5. ios::trunc 若文件存在先删除,在创建
  6. ios::binary 二进制方式打开

#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ofstream ofs;//创建流对象 ->往文件里写
ofs.open("123.txt",ios::app);//打开文件123.txt如果没有会自动创建,
ofs << "我们可以写入文件了!";
ofs << "啊哈!我又写了一行";//这行会追加在上一行后面
ofs.close();//关闭文件


return 0;
}

我们将文件中写好的数据读出

第一种读法

#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ifstream ifs("123.txt", ios::in);//创建流对象并按指定方式打开;ifstream ifs;ifs.open("123.txt",ios::in)等价
if (!ifs.is_open())
{
cout << "文件不存在" << endl;
}
char arr[1024] = { 0 };
while (ifs >> arr)
{
cout << arr << endl;
}
ifs.close();
return 0;
}

第二种读法

#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ifstream ifs("123.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件不存在" << endl;
}
char arr[1024] = { 0 };
while (ifs.getline(arr, sizeof(arr)))//按行读取
{
cout << arr << endl;
}
ifs.close();
return 0;
}

 

 第三种字符串读取

#include<iostream>
#include<string>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ifstream ifs("123.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件不存在" << endl;
}
string arr;
while (getline(ifs, arr))
{
cout << arr << endl;
}

ifs.close();
return 0;
}

 

二进制读写 文件

  1. read()它属于ifs的成员函数,读取时需要调用
  2. write()它属于ofs的成员函数,写入时需要调用
#include<iostream>
#include<string>
#include<fstream>//包含头文件
using namespace std;
struct student
{
string name;
int age;
};
int main()
{
ofstream ofs("12.txt", ios::out | ios::binary);
student one = { "小明",12 };
ofs.write((const char*)&one,sizeof(one));//我先将小明信息存入并关闭文件
ofs.close();
ifstream ifs("12.txt", ios::in | ios::binary);//我打开文件进行读取
if (!ifs.is_open())
{
cout << "文件不存在" << endl;
}
ifs.read(( char*)&one, sizeof(one));
cout <<"姓名:"<< one.name <<"年龄:"<< one.age << endl;
ifs.close();
return 0;
}

举报

相关推荐

0 条评论