前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++ 读写文本文件和二进制文件

C++ 读写文本文件和二进制文件

作者头像
我与梦想有个约会
发布2023-10-20 16:53:45
1660
发布2023-10-20 16:53:45
举报
文章被收录于专栏:jiajia_dengjiajia_deng

在 C 中,我们通过 FILE 结构体生成的指向 FILE 结构体的指针来操作文件。其提供了诸如 fgetc、fgets、feof等等函数,在 C++ 中重新封装了操作文件的方法,其实现在 iostream 派生的 fstream 中,实际内部实现基本原理与 C 相同。下面就分别介绍下操作文本文件和二进制文件的方法。

【操作文本文件】

代码语言:javascript
复制
#include 
#include 
 
using namespace std;
 
bool txt_write()
{
ofstream ofs(“abc.txt”, ios::out  ios::trunc);
if (!ofs) return false;
 
ofs << “aaaaaaaaaaaaa” << endl;
ofs << “bbbbbbbbbbbbb” << endl;
ofs << “ccccccccccccc” << endl;
 
ofs.close();
return true;
}
 
bool txt_read()
{
ifstream ifs(“abc.txt”, ios::in);
if (!ifs) return false;
 
/*
char buf[1024];
getline 方式, 读取不包含换行
while (ifs.getline(buf, 1024), !ifs.eof())
{
cout << buf << endl;
}
*/
 
// get 方式
char ch;
while (ifs.get(ch), !ifs.eof())
{
cout << ch;
}
 
ifs.close();
return true;
}
 
int main(int argc, char* argv[])
{
//txt_write();
txt_read();
return 0;
}

以上只介绍了一些简单的读写操作,更多的方法可以参考 fstream 的其他成员方法。 【操作二进制文件】

代码语言:javascript
复制
#include 
#include 
#include 
 
using namespace std;
 
struct Student
{
char name[100];
int num;
int age;
char sex;
};
 
bool file_write()
{
Student s[3] = {
{“dengjia”, 1001, 18, ‘f’},
{“jiadeng”, 1002, 21, ‘m’},
{“beijing”, 1003, 22, ‘f’}
};
 
ofstream ofs(“student.data”, ios::out  ios::binary);
if (!ofs) return false;
 
for (int i = 0; i < 3; i++)
{
// 将每个结构体的首地址指针传递给write
// 它会根据你第二个参数给出的大小读取并写入数据到文本。
ofs.write((char*)&s[i], sizeof(s[i]));
}
 
ofs.close();
return true;
}
 
bool file_read()
{
Student s;
ifstream ifs(“student.data”, ios::in  ios::binary);
if (!ifs) return false;
 
while (ifs.read((char*)&s, sizeof(Student)), !ifs.eof())
{
cout << s.name << endl;
cout << s.age  << endl;
cout << s.num  << endl;
cout << s.sex  << endl;
}
 
ifs.close();
return true;
}
 
int _tmain(int argc, char* argv[])
{
// file_write();
file_read();
return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-05-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档