当前位置: 首页 > news >正文

【C++ 标准流,文件流】

C++ 标准流,文件流

  • ■ 标准输入,输出流,
  • ■ 文件流(ofstream写入,ifstream读取,fstream创建-写入-读取)
    • ■ open()
    • ■ ofstream
    • ■ ifstream
    • ■ 流插入<<
    • ■ 文件位置指针

■ 标准输入,输出流,

iostream 标准库,它提供了 cin 和 cout 方法

■ 文件流(ofstream写入,ifstream读取,fstream创建-写入-读取)

1. C++ 源代码文件中包含头文件 <iostream><fstream>2. 
数据类型描述
ofstream该数据类型表示输出文件流,用于创建文件并向文件写入信息。
ifstream该数据类型表示输入文件流,用于从文件读取信息。
fstream该数据类型通常表示文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。

■ open()

void open(const char *filename, ios::openmode mode);

模式标志描述
ios::app追加模式。所有写入都追加到文件末尾。
ios::ate文件打开后定位到文件末尾。
ios::in打开文件用于读取。
ios::out打开文件用于写入。
ios::trunc如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0。

■ ofstream

以写入模式打开文件,并希望截断文件,以防文件已存在

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );

■ ifstream

打开一个文件用于读写

ifstream  afile;
afile.open("file.dat", ios::out | ios::in );

■ 流插入<<

流插入运算符( << )向文件写入信息

ifstream  afile;
afile.open("file.dat", ios::out | ios::in );

示例一:

#include <fstream>
#include <iostream>
using namespace std;int main ()
{char data[100];// 以写模式打开文件ofstream outfile;outfile.open("afile.dat");cout << "Writing to the file" << endl;cout << "Enter your name: "; cin.getline(data, 100);// 向文件写入用户输入的数据outfile << data << endl;cout << "Enter your age: "; cin >> data;cin.ignore();// 再次向文件写入用户输入的数据outfile << data << endl;// 关闭打开的文件outfile.close();// 以读模式打开文件ifstream infile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // 在屏幕上写入数据cout << data << endl;// 再次从文件读取数据,并显示它infile >> data; cout << data << endl; // 关闭打开的文件infile.close();return 0;
}
当上面的代码被编译和执行时,它会产生下列输入和输出:$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

■ 文件位置指针

istream 和 ostream 都提供了用于重新定位文件位置指针的成员函数。
这些成员函数包括关于
istream 的 seekg(“seek get”)
ostream 的 seekp(“seek put”)
seekg 和 seekp 的参数通常是一个长整型。

// 定位到 fileObject 的第 n 个字节(假设是 ios::beg)
fileObject.seekg( n );// 把文件的读指针从 fileObject 当前位置向后移 n 个字节
fileObject.seekg( n, ios::cur );// 把文件的读指针从 fileObject 末尾往回移 n 个字节
fileObject.seekg( n, ios::end );// 定位到 fileObject 的末尾
fileObject.seekg( 0, ios::end );
http://www.lryc.cn/news/311510.html

相关文章:

  • 【排序】详解冒泡排序
  • 什么是Docker容器?
  • (C++练习)选择题+编程题
  • 【鸿蒙开发】第十五章 ArkTS基础类库-并发
  • 华为数通方向HCIP-DataCom H12-821题库(多选题:21-40)
  • 【简单模拟】第十三届蓝桥杯省赛C++ B组《刷题统计》(c++)
  • IO-DAY3
  • python实现常见一元随机变量的概率分布
  • 微服务学习
  • 【.NET Core】深入理解IO - 读取器和编写器
  • 【Java项目介绍和界面搭建】拼图小游戏——添加图片
  • 「MySQL」基本操作类型
  • Android 14 权限
  • Springboot整合SSE实现实时消息推送
  • 在pytorch中利用GPU训练神经网络时代码的执行顺序并提高训练效率
  • vue3学习
  • 毫秒生成的时间戳如何转化成东八区具体时间
  • 02. Nginx入门-Nginx安装
  • leetcode73. 矩阵置零
  • 【中间件】RabbitMQ入门
  • rtt的io设备框架面向对象学习-电阻屏LCD设备
  • 商城免费搭建之java商城 java电子商务Spring Cloud+Spring Boot+mybatis+MQ+VR全景
  • 蓝桥杯刷题--python-16
  • 闰年计算中的计算机Bug
  • python水表识别图像识别深度学习 CNN
  • Java对接快递100实时快递单号查询API接口
  • Redis常见的15个【坑】,避坑指南
  • 04. Nginx入门-Nginx WEB模块
  • Python在信息安全领域中具有重要的作用
  • Linux 定时备份文件到另一台服务器