c++教程2021-6-19学习笔记
2021/6/21 14:28:20
本文主要是介绍c++教程2021-6-19学习笔记,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <fstream>//文件读写的头文件。 /** *文件操作:持久化数据。 * 文件存储形式:文本文件/二进制文件 */ /** * 读文件:ifsteam 读文件 * 写文件:ofstream 输出到文件中。 * 读写操作:fsteam */ //写文件步骤: //1.包含头文件 #include <fstream> //2.创建流对象。 //3.打开文件。ios::in 读文件 ios::out 写文件 ios::binary 二进制 //4.写文件。 //5.关闭流。 void writeFile() { //1.包含头文件 #include <fstream> //2.创建流对象。 ofstream ofs; //3.打开文件。ios::in 读文件 ios::out 写文件 ios::binary 二进制 ofs.open("wirte.txt",ios::out); //4.写文件。 ofs<<"姓名:张三"<<endl; ofs<<"性别:男"<<endl; ofs<<"年龄:18"<<endl; //5.关闭流。 ofs.close(); } void readFile() { //1.包含头文件 #include <fstream> //2.创建流对象。 ifstream ifs; //3.打开文件。 ifs.open("wirte.txt",ios::in); //判断文件是否打开成功。 if(!ifs.is_open()){ cout << "文件打开失败。"<<endl; return; } //4.四种方式读文件。 //第一种方式: // char buf[1024] = {0}; // while(ifs >> buf){ // cout << buf<<endl; // } //第二种方式: // char buf[1024] = {0}; // while(ifs.getline(buf,sizeof (buf))){ // cout << buf<< endl; // } //第三种 // string buf; // while(getline(ifs,buf)){ // cout << buf<<endl; // } //第四种:EOF 文件尾部的标志。 char c; while((c=ifs.get())!= EOF){ cout << c<<endl; } //5.关闭流。 ifs.close(); } int main() { // writeFile(); readFile(); return 0; } #include <fstream> /** * 通过二进制的形式对文件进行读写。 */ class Person145 { public : char m_Name[64]; int m_Age; }; void writeF() { //1,包含头文件。 //2,创建写文件流。 ofstream ofs; //3.打开文件。 ofs.open("person.txt", ios::out | ios::binary); //4.写内容。 Person145 person145; strcpy(person145.m_Name, "张三"); person145.m_Age = 18; ofs.write((const char *) &person145, sizeof(Person145)); //5.关闭流 ofs.close(); } void readF() { //1,包含头文件。 //2,创建写文件流。 ifstream ifs; //3.打开文件。 ifs.open("person.txt", ios::in | ios::binary); if (!ifs.is_open()){ cout <<"打开文件失败。"<<endl; return; } //4.读内容。 Person145 person145; ifs.read((char *)&person145,sizeof (person145)); cout << person145.m_Name << "," << person145.m_Age<<endl; //5.关闭流 ifs.close(); } int main() { // writeF(); readF(); return 0; }
这篇关于c++教程2021-6-19学习笔记的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28pyqt 怎么打包整个项目-icode9专业技术文章分享
- 2024-09-28laravel Commands 创建带有参数的 Artisan 命令的步骤和示例-icode9专业技术文章分享
- 2024-09-28antd怎么实现渲染tiff图片-icode9专业技术文章分享
- 2024-09-28英文半角中划线和中文全角的中划线有什么区别-icode9专业技术文章分享
- 2024-09-28nvm npm 和node 他们之间有什么关系-icode9专业技术文章分享
- 2024-09-28Node Version Manager (nvm)使用教程-icode9专业技术文章分享
- 2024-09-28nvm命令太慢,是什么原因-icode9专业技术文章分享
- 2024-09-28Kotlin 如何增加、删除和修改 MutableStateFlow 中的值。-icode9专业技术文章分享
- 2024-09-28Kotlin的stateFlow.update 写法介绍-icode9专业技术文章分享
- 2024-09-28kotlin 怎么获取当前时间格式-icode9专业技术文章分享