1.1
1.1.1文件处理头文件
#include
#include
1.1.2创建流对象打开文件
···fstream file(“file.txt”,ios::out)
等同于fstream file;file.open(“file.txt”,ios::out)
···类型: ifstream//从文档输入,默认ios::in
ofstream//向文档输出,默认ios::out
fstream//输入输出,默认ios::in
···打开方式:
ios::in输入
ios::out清空后输入,与ios::in合用不清空,定位到位置0。
ios::ate不清空,定位到文件尾,可配合指针在任何地方修改文档
ios::app不清空,只能在文件尾添加数据,指针对其无效
ios::trunc清空文档
ios::binary二进制格式打开//写入定长记录必要
详解:
ofstream流,以ios::app打开(或者“ios::app|ios::out”),如果没有文件,那么生成空文件;如果有文件,那么在文件尾追加。
以ios::app|ios::in打开,不管有没有文件,都是失败。
以ios::ate打开(或者”ios::ate|ios::out”),如果没有文件,那么生成空文件;如果有文件,那么清空该文件
以ios::ate|ios::in打开,如果没有文件,那么打开失败;如果有文件,那么定位到文件尾,并可以写文件,但是不能读文件

ifstream流,以ios::app打开(“ios::app|ios::out”),不管有没有文件,打开都是失败。
以ios::ate打开(“ios::ate|ios::out”),如果没有文件,打开失败
如果有文件,打开成功,并定位到文件尾,但是不能写文件

fstream流,默认是ios::in,所以如果没有文件,ios::app和ios::ate都是失败,
以ios::app|ios::out,如果没有文件则创建文件,如果有文件,则在文件尾追加
以ios::ate|ios::out打开,如果没有文件则创建文件,如果有,则清空文件。
以ios::ate|ios::out|ios::in打开,如果没有文件,则打开失败,有文件则定位到文件尾

可见:ios::app不能用来打开输入流,即不能和ios::in相配合
而ios::ate可以和ios::in配合,此时定位到文件尾;如果没有ios::in相配合而只是同ios::out配合,那么将清空原文件
(ios::ate|ios::in–>在原文件尾追加内容;ios::ate—>清空原文件,ios::out是默认必带的,可加上也可不加,对程序无影响)
以ios::app方式打开文件,即使修改文件指针,也只能输出到文件尾。实际上以ios::app打开的文件的写入,和文件指针五关。
(ate和app的关键区别,app只能在尾部追加,ate可以配合指针修改文件中的部分内容。)
ios::ate如果不和ios::in配合的话,将清空原文件
1.1.3测试是否成功打开
if(!file)//或者if(file.is_open())该函数文档成功打开则返回1
{cerr<<“file can not be opened.\n”;
exit(“EXIT_FAILURE”);//参数为EXIT_SUCCESS时正常退出程序,其他参数异常退出程序。参数定义在中
}
1.1.4指针
ifstream seekg();//读指针
tellg();//返回长整型的指针位置,即字节数
ofstream seekp();//写指针
tellp();
fstream seekg()/seekp()//功能完全一样,读写指针实际上同步
tellg()/tellp()
seekg(long int a,ios::seek_dir b)//b默认是ios::beg,还可取值ios::cur,ios::end。b为ios::cur时a正向文件尾,负向文件头,其他
俩情况正负随便.
file.seekp(5sizeof(className/objectName)) ; //类的所有对象大小一样
1.1.5流对象的输入输出
file>>…
file<<…//输出覆盖原文件内容
1.1.6文件结束与关闭
···while(file>>a)//文件末尾都有文件结束符,读到EOF流返回0指针即0,自动退出循环
···while(!file.eof()){};
file.clear();//reset eof
file.seekg(0);
…关闭file.close();
1.1.7随机存取
file.write(reinterpret_cast<const char
>(&number),sizeof(number));从第一个参数的字节流读取第二个参数个字节输出到file
file.read(reinterpret_cast<const char*>(&number),sizeof(number));//从file的字节流读取第二个参数个字节输入到number
注意:write()是覆盖输出!!原来的被覆盖了。

2.经典例题❤

//Student.h
#include <string>
//身份证号码,学生的名字,学生的姓氏和学生的成绩。
class Student
{public:Student(const int =0, const std::string & = "", const std::string & = "", double = 0.0);void setID(int);int getID() const;// accessor functions for lastNamevoid setLastName(const std::string&);std::string getLastName() const;// accessor functions for firstNamevoid setFirstName(const std::string&);std::string getFirstName() const;// accessor functions for balancevoid setGrade(double);double getGrade()const;private:int ID;char lastName[15];char firstName[10];double grade;}; // end class ClientData
#include <iostream>
#include <fstream>
#include <iomanip>
#include<vector>
#include <cstdlib> // exit function prototype
#include "Student.h" // ClientData class definition
using namespace std;
int enterChoice();
void createTextFile(fstream& readFromFile);
void updateRecord(fstream& File);
void newRecord(fstream& File);
void deleteRecord(fstream& File);
void outputLine(ostream& output, const Student& record);
int getSize(const vector<Student>&);
void printA();
/*每个学生应获得一个身份证号码,学生的名字,学生的姓氏和学生的成绩。
为每个学生获取的数据构成学生的记录,并应存储在名为student的类的对象中。程序应将记录保存在用户指定的二进制文件中(例如“文件.dat”).该计划还应能够:(1) 显示所有记录(连同学生的平均分)(2) 添加 / 删除记录(3)更新每条记录*/
vector<Student>a(100);
enum Choices { PRINT = 1, UPDATE, NEW, DELETE, END };
int main()
{fstream outCredit("file.dat", ios::out | ios::in | ios::trunc);//| ios::binary  if (!outCredit){cerr << "File could not be opened." << endl;exit(EXIT_FAILURE);}else {cout << "successful \nplease enter the number of students n ?\n";}// try added beginint id = 0;double grade = 0.0;string firstname = "", lastname = "";Student student;student.setID(id);student.setLastName(lastname);student.setFirstName(firstname);student.setGrade(grade);// ctry added ended for (int i = 0; i < 100; ++i)//cout << "i = " << i << endl;{Student k;a[i] = k;};//outCredit.write(reinterpret_cast<const char*>(&student),sizeof(Student));int choice;while ((choice = enterChoice()) != END){switch (choice){case PRINT: // create text file from record filecreateTextFile(outCredit);printA();break;case UPDATE: // update recordupdateRecord(outCredit);printA();break;case NEW: // create recordnewRecord(outCredit);printA();break;case DELETE: // delete existing recorddeleteRecord(outCredit);printA();break;default: // display error if user does not select valid choicecerr << "Incorrect choice" << endl;break;};outCredit.clear();//reset eof};
}; // end main
int enterChoice()
{cout << "\nEnter your choice" << endl<< "1 - store a formatted text file of students" << endl<< "    called \"print.txt\" for printing" << endl<< "2 - update a student" << endl<< "3 - add a new student" << endl<< "4 - delete an student" << endl<< "5 - end program\n? ";int menuChoice;cin >> menuChoice; // input menu selection from userreturn menuChoice;
}
void createTextFile(fstream& readFromFile)
{ofstream outPrintFile("print.txt", ios::out | ios::trunc);Student g;int a_size = getSize(a);if (!outPrintFile){cerr << "File could not be created." << endl;exit(EXIT_FAILURE);}outPrintFile << left << setw(10) << "ID" << setw(16)<< "Last Name" << setw(11) << "First Name" << right << setw(10) << "grade\n";cout << "outprintfile is finished \n";readFromFile.seekg(0, ios::beg);readFromFile.read(reinterpret_cast<char*>(&g), sizeof(Student));while (!readFromFile.eof()){outputLine(outPrintFile, g);readFromFile.read(reinterpret_cast<char*>(&g), sizeof(Student));};int p = getSize(a);double all = 0;for (int i = 0;i < p;i++){all += a[i].getGrade();}//outPrintFile << "\nAverage is " << all / p << endl;cout << "\nAverage is " << all / p << endl;
};
void outputLine(ostream& output, const Student& record)
{output << left << setw(10) << record.getID()<< setw(16) << record.getLastName()<< setw(11) << record.getFirstName()<< setw(10) << setprecision(2) << right << fixed<< showpoint << record.getGrade() << endl;
};
void updateRecord(fstream& File)
{int h;cout << "Enter ID to update\n";cin >> h;int i;for (i = 0;i < 100;++i){if (a[i].getID() == h){int m = 0;string  s = "";double d = 0;int k;enum Choice2 { ID = 1, firstName, LastName, grade };cout << "choose1-4:1 change ID \n2 change firstName \n3 change lastname \n4 change grade\n";cout << "begin i = " << i << endl;cin >> k;switch (k){case 1:cout << "enter new ID: \n";cin >> m;a[i].setID(m);break;case 2:cout << "enter new first name\n";cin >> s;a[i].setFirstName(s);break;case 3:cout << "enter new lastname\n";cin >> s;a[i].setLastName(s);break;case 4:cout << "enter new grade\n";cin >> d;a[i].setGrade(d);break;}break;}};cout << "get out  i = " << i << endl;File.seekp(i* sizeof(Student), ios::beg);cout << "seekp ok ";File.write(reinterpret_cast<const char*>(&a[i]), sizeof(Student));} // end function updateRecord
void newRecord(fstream& File)
{int id;double grade;string  s1, s2;cout << "enter ID(int),firstName,LastName,grade\n";cin >> id >> s1 >> s2 >> grade;//a[getSize(a)]=Student(i, s2, s1, d);  //出错int index = getSize(a);a[index].setID(id);a[index].setFirstName(s1);a[index].setLastName(s2);a[index].setGrade(grade);{ cout << "new print begin \n";cout << setw(10) << "ID" << setw(16)<< "First Name" << setw(11) << "Last Name" << right << setw(10) << "grade" << endl;cout << setw(10) << a[index].getID() << setw(16) << a[index].getFirstName() << setw(11) << a[index].getLastName() << right << setw(10) << a[index].getGrade() << endl;cout << "new print end\n\n";}File.seekp((index) * sizeof(Student), ios::beg);File.write(reinterpret_cast<const char*>(&a[index]), sizeof(Student));
};
void deleteRecord(fstream& File)
{int h;cout << "Enter ID to delete\n";cin >> h;int i;for (i = 0;;++i){if (a[i].getID() == h){a.erase(a.begin() + i);break;}};cout << "delete i = " << i << endl;File.seekp(i* sizeof(Student), ios::beg);cout << "seekp ok " << endl;for (int j = i; j < 99; j++) {cout << "delete rewirite   " << j << endl;File.write(reinterpret_cast<const char*>(&a[j]), sizeof(Student));}
}
int getSize(const vector<Student>& a)
{for (int i = 0;i < 100;i++){if (a[i].getID() == 0)return i;}
};
void printA() {int num = getSize(a);cout << setw(10) << "ID" << setw(16)<< "First Name" << setw(11) << "Last Name" << right << setw(10) << "grade" << endl;for (int k = 0; k < num; k++) {cout << setw(10) << a[k].getID() << setw(16) << a[k].getFirstName() << setw(11) << a[k].getLastName() << right << setw(10) << a[k].getGrade() << endl;}
}

C++笔记 文件处理笔记相关推荐

  1. 记笔记-文件记笔记方法

    0.前言 最近发现记录上一篇博客笔记中的方法(快速利用工具编写博客:(https://blog.csdn.net/qq_33125039/article/details/84432391))出现问题: ...

  2. Linux学习笔记-文件权限与路径

    Linux学习笔记-文件与目录 目前从电子信息科学与技术转到了计算机专业,因此想趁着大四比较闲的时候补一些计算机的知识.我想说:你好,生活[斜眼笑]!愿生活温柔以待!哈哈,这是我写的第一篇博客,谨以此 ...

  3. Linux学习笔记 文件服务Vsftp详细介绍

    Linux学习笔记 文件服务Vsftp详细介绍 知识点: 1.FTP使用TCP连接和TCP端口 2.在进行通信时,FTP需要建立两个TCP连接: 一个用于控制信息,TCP端口号缺省为21 一个用于数据 ...

  4. 【C语言程序设计进阶-浙大翁恺】C语言笔记 文件

    [C语言程序设计进阶-浙大翁恺]C语言笔记 文件 文件 格式化输入输出 文件输入输出 二进制文件 位运算 按位运算 移位运算 位运算例子 位段 文件 格式化输入输出 %-nd:数字左对齐,且输出要占n ...

  5. SRE运维工程师笔记-文件查找和压缩

    SRE运维工程师笔记-文件查找和压缩 1. 文件查找 1.1 locate 1.2 find 1.2.1 指定搜索目录层级 1.2.2 对每个目录先处理目录内的文件,再处理目录本身 1.2.3 根据文 ...

  6. 神马笔记 版本1.8.0——删除笔记/文件夹·技术细节篇

    神马笔记 版本1.8.0--删除笔记/文件夹·技术细节篇 一.目标 二.体验地址 三.技术问题 1. 拖拽排序问题 2. indexOf问题 四.Finally 一.目标 记录开发过程中的2个技术问题 ...

  7. 神马笔记 版本1.8.0——删除笔记/文件夹·代码篇

    神马笔记 版本1.8.0--删除笔记/文件夹·代码篇 一.目标 二.体验地址 三.功能设计 1. 实现删除功能 2. 处理最近删除的可见性 四.实现过程 1. 删除到最近删除 2. 从最近删除恢复 3 ...

  8. web漏洞“小迪安全课堂笔记”文件操作安全,文件包含

    小迪安全课堂笔记文件包含 思维导图 原理 白盒 黑盒 看参数及功能点 本地包含 无限制,跨目录../../www.txt 有限制,增加了后缀html %00截断绕过 长度截断绕过 远程包含 无限制 有 ...

  9. 《算法笔记》学习笔记(1)

    <算法笔记>学习笔记(1) 2021/4/7号 晚上21:36开始学习 第二章 c++/c快速入门 有的时候不要在一个程序中同时使用cout 和 printf 有的时候会出现问题. 头文件 ...

最新文章

  1. 数据智能与计算机图形学领域推荐论文列表
  2. if var matlab,matlab中if 语句后面的判别式不能是算术表达式?或者说变量?
  3. 搜索引擎学习(四)中文分词器
  4. 基本数据类型和包装类型
  5. H - Great Cells Gym - 101194H(数学推导/思维)
  6. Google Analytics异步代码-创建虚拟浏览量跟踪
  7. Linux下如何从普通用户切换到root用户
  8. idea中Tomcat启动乱码问题
  9. First Kernel-pwn
  10. Kotlin 一种以服务为基础的APP架构及源码示例
  11. 图解DbgView使用
  12. 如何将自己的电脑做成服务器
  13. lumerical FDTD自学日记
  14. kettle设置mysql时区_kettle中通过 时间戳(timestamp)方式 来实现数据库的增量同步操作(一)...
  15. 年薪90万的阿里p7和副处级干部选哪个?
  16. 什么是云中台系统_“生于云中”的优势是真实的,但不是绝对的
  17. 考研数一英语二计算机,考研常识 | 我是考英语一还是英语二?数一二三都有什么区别...
  18. 裁剪图像的黑边(图像拼接后的黑边去除)
  19. 简易实现AI虚拟鼠标—手势控制鼠标
  20. 有哪些简单好用的国产数据库?

热门文章

  1. mysql mpm_Zabbix Mysql Fpmmm(MPM)监控的教程
  2. 印象笔记(evernote)支持MarkDown语法
  3. 正则html在线测试,正则表达式在线测试工具
  4. node.js读取文件中文乱码问题
  5. 【AutoSAR】【MCAL】PWM
  6. 速读原著-UnixLinux基础(七)
  7. 几种贴图压缩方式详解
  8. pytest中参数化方法,并且根据执行的命令进行动态参数化
  9. win11忘记当前密码怎么办
  10. 电压源电流源电路符号及2B法