栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++::Stream

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++::Stream

文件流
// 头文件
#include

// 类型
文本文件;
二进制文件;

// 操作文件的三大类
ofstream:写;
ifstream:读;
fstream:读写;
写文件
// 步骤
#include
ofstream ofs;  // 创建流对象
ofs.open("path",打开方式);  // 打开文件
ofs << "写入内容" << endl;  // 写入的内容
ofs.close();  // 关闭文件


// 打开方式
ios::in  读打开;
ios::out  写打开;
ios::ate  设置初始位置为文件尾;
ios::app  追加写;
ios::trunc  如果文件存在,先删除,再创建;
ios::binary  二进制方式打开;

// 文件打开方式可以配合使用,利用 | 操作符
读文件
// 步骤
#include
ifstream ifs;  // 创建流对象
ifs.open("path",打开方式);  // 打开文件并判断文件是否打开成功
if ( !ifs.is_open()){}
// 读取数据,四种方式
ifs.close();  // 关闭文件


// 读数据

// 1
char buf[1024] = {0};
while (ifs >> buf)
{
    cout << buf << endl;
}

// 2
char buf[1024] = {0};
while (ifs.getline(buf,sizeof(buf))){
    cout << but << endl;
}

// 3 
string buf;
while (getline(ifs,buf)){
    cout << buf << endl;
}

// 4
char c;
while ((c = ifs.get()) != EOF)){  // 一个一个字符读
    cout << c;
}
二进制方式
// 二进制方式写文件主要利用流对象调用成员函数write
// 函数原型
ostream& write(const char* buffer,int len);
// len表示读写的字节数
// 可以写入对象,但是需要把类型强转为(const char*)类型

// 读主要利用read
// 函数原型
ifstream& read(char *buffer,int len);
// 读出对象类型强转为(char*)

// 怎么写的怎么读,写的什么读什么。
IO对象无拷贝或赋值

进行io操作的函数通常以引用方式传递和返回流

刷新输出缓冲区
std::cout << "h" << std::endl; // 输出一个h和一个换行符,然后刷新缓冲
std::cout << "h" << std::flush; // 输出一个h,然后刷新缓冲
std::cout << "h" << std::ends; // 输出一个h和一个空字符,然后刷新缓冲

// unitbuf操作符
std::cout << std::unitbuf; // 设置所有的输出操作后会立即刷新缓冲
std::cout << std::nounitbuf; // 取消设置
文件输入输出
#include // 文件输入输出相关头文件
ifstream 读
ofstream 写
fstream 读写


std::string str;
std::ifstream in("study.txt"); // 设定一个输入流
in >> str; // 依照空格,换行符分割
std::cout << str << std::endl;


// 文件打开模式
in 读
out 写
app 追加
ate 打开文件后移动到文件尾
trunc 截断文件
binary 以二进制方式打开
std::ofstream out("path",std::ofstream::out | std::ofstream::app)
字符串流
#include

istringstream 从string中读数据
strm.str(); // 返回strm所保存的string的拷贝
strm.str(s); // 将s拷贝到strm中,返回void
strm >> s; // 将strm中的内容输出到s中,按照空白分割

ostringstream 向string中写数据
ostrm << s; // 将s写入到ostrm中


std::map> m1;
std::ifstream in("study.txt");
std::istringstream is;
std::string line,word;
int count = 1;

while (std::getline(in, line))
{
     is.str(line);
     while (is >> word)
        {
            m1[word].push_back(count);
        }
    count++;
    is.clear(); // 对于重复使用的流,一定要记得复原其状态,使其可用
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/997712.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号