当前位置: 首页 > 编程日记 > 正文

C++中fstream的使用

C++中处理文件类似于处理标准输入和标准输出。类ifstream、ofstream和fstream分别从类 istream、ostream和iostream派生而来。作为派生的类,它们继承了插入和提取运算符(以及其他成员函数),还有与文件一起使用的成员和构造函数。可将文件<fstream> 包括进来以使用任何fstream。如果只执行输入,使用ifstream类;如果只执行输出,使用 ofstream类;如果要对流执行输入和输出,使用fstream类。可以将文件名称用作构造函数参数。

ofstream: Stream class to write on files.

ifstream: Stream class to read from files.

fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream and ostream.

对这些类的一个对象所做的第一个操作通常就是将它和一个真正的文件联系起来,也就是说打开一个文件。被打开的文件在程序中由一个流对象(stream object)来表示 (这些类的一个实例) ,而对这个流对象所做的任何输入输出操作实际就是对该文件所做的操作。

要通过一个流对象打开一个文件,可以使用它的成员函数open()或直接通过构造函数。

void open (constchar * filename, openmode mode);

这里filename 是一个字符串,代表要打开的文件名,mode 是以下标志符的一个组合:

ios::in  以输入(读)方式打开文件;

ios::out  以输出(写)方式打开文件;

ios::ate  初始位置:文件尾,文件打开后定位到文件尾;

ios::app  以追加的方式打开文件,所有输出附加在文件末尾;

ios::trunc  如果文件已存在则先删除该文件;

ios::binary  二进制方式,以二进制方式打开文件;

这些标识符可以被组合使用,中间以”或”操作符(|)间隔。

这些类的成员函数open 都包含了一个默认打开文件的方式,只有当函数被调用时没有声明方式参数的情况下,默认值才会被采用。如果函数被调用时声明了任何参数,默认值将被完全改写,而不会与调用参数组合。ofstream类的默认打开方式是: ios::out | ios::trunc ;ifstream 类的默认打开方式是ios::in;fstream类的默认打开方式是: ios::in | ios::out.

http://www.cplusplus.com/reference/fstream/fstream/中列出了fstream中可以使用的成员函数。

C++ IO heads, templates and class (https://www.ntu.edu.sg/home/ehchua/programming/cpp/cp10_IO.html):


以下是测试代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>#include "fstream.hpp"/* reference: http://www.tutorialspoint.com/cplusplus/cpp_files_streams.htmhttps://www.ntu.edu.sg/home/ehchua/programming/cpp/cp10_IO.htmlhttp://www.bogotobogo.com/cplusplus/fstream_input_output.php
*/int test_file_size()
{std::ifstream in("E:/GitCode/Messy_Test/testdata/fstream_data.bin", std::ios::binary);if (!in.is_open()) {std::cout << "fail to open file\n";return -1;}std::streampos begin, end;begin = in.tellg();in.seekg(0, std::ios::end);end = in.tellg();in.close();std::cout << "this file's size is: " << (end - begin) << " bytes.\n";return 0;
}int test_fstream1()
{char data[100];// open a file in write mode.std::ofstream outfile;outfile.open("E:/GitCode/Messy_Test/testdata/fstream.dat");if (!outfile.is_open()) {std::cout << "fail to open file to write\n";return -1;}std::cout << "Writing to the file" << std::endl;std::cout << "Enter your name: ";std::cin.getline(data, 100);// write inputted data into the file.outfile << data << std::endl;std::cout << "Enter your age: ";std::cin >> data;std::cin.ignore();// again write inputted data into the file.outfile << data << std::endl;// close the opened file.outfile.close();// open a file in read mode.std::ifstream infile;infile.open("E:/GitCode/Messy_Test/testdata/fstream.dat");if (!infile.is_open()) {std::cout << "fail to open file to read\n";return -1;}std::cout << "Reading from the file" << std::endl;infile >> data;// write the data at the screen.std::cout << data << std::endl;// again read the data from the file and display it.infile >> data;std::cout << data << std::endl;// close the opened file.infile.close();return 0;
}int test_fstream2()
{/* Testing Simple File IO (TestSimpleFileIO.cpp) */std::string filename = "E:/GitCode/Messy_Test/testdata/test.txt";// Write to Filestd::ofstream fout(filename.c_str());  // default mode is ios::out | ios::truncif (!fout) {std::cerr << "error: open file for output failed!" << std::endl;abort();  // in <cstdlib> header}fout << "apple" << std::endl;fout << "orange" << std::endl;fout << "banana" << std::endl;fout.close();// Read from filestd::ifstream fin(filename.c_str());  // default mode ios::inif (!fin) {std::cerr << "error: open file for input failed!" << std::endl;abort();}char ch;while (fin.get(ch)) {  // till end-of-filestd::cout << ch;}fin.close();return 0;
}int test_fstream3()
{/* Testing Binary File IO (TestBinaryFileIO.cpp) */std::string filename = "E:/GitCode/Messy_Test/testdata/test.bin";// Write to Filestd::ofstream fout(filename.c_str(), std::ios::out | std::ios::binary);if (!fout.is_open()) {std::cerr << "error: open file for output failed!" << std::endl;abort();}int i = 1234;double d = 12.34;fout.write((char *)&i, sizeof(int));fout.write((char *)&d, sizeof(double));fout.close();// Read from filestd::ifstream fin(filename.c_str(), std::ios::in | std::ios::binary);if (!fin.is_open()) {std::cerr << "error: open file for input failed!" << std::endl;abort();}int i_in;double d_in;fin.read((char *)&i_in, sizeof(int));std::cout << i_in << std::endl;fin.read((char *)&d_in, sizeof(double));std::cout << d_in << std::endl;fin.close();return 0;
}int test_fstream4()
{std::string theNames = "Edsger Dijkstra: Made advances in algorithms, the semaphore (programming).\n";theNames.append("Donald Knuth: Wrote The Art of Computer Programming and created TeX.\n");theNames.append("Leslie Lamport: Formulated algorithms in distributed systems (e.g. the bakery algorithm).\n");theNames.append("Stephen Cook: Formalized the notion of NP-completeness.\n");std::ofstream ofs("E:/GitCode/Messy_Test/testdata/theNames.txt");if (!ofs)	{std::cout << "Error opening file for output" << std::endl;return -1;}ofs << theNames << std::endl;ofs.close();char letter;int i;std::string line;std::ifstream reader("E:/GitCode/Messy_Test/testdata/theNames.txt");if (!reader) {std::cout << "Error opening input file" << std::endl;return -1;}//for (i = 0; !reader.eof(); i++) {while (!reader.eof()) {reader.get(letter);std::cout << letter;//getline( reader , line ) ;//std::cout << line << std::endl;}reader.close();return 0;
}//
std::ofstream _file;int test_init_database()
{_file.open("E:/GitCode/Messy_Test/testdata/data.bin");if (!_file.is_open()) {fprintf(stderr, "open file fail\n");return -1;}return 0;
}int test_store_database()
{for (int i = 0; i < 10; ++i) {_file.write((char*)&i, sizeof(i));}return 0;
}int test_close_database()
{_file.close();return 0;
}int test_fstream5()
{test_init_database();for (int i = 0; i < 5; ++i) {test_store_database();}test_close_database();std::ifstream file("E:/GitCode/Messy_Test/testdata/data.bin");if (!file.is_open()) {fprintf(stderr, "open file fail\n");return -1;}int a[100];for (int i = 0; i < 50; ++i) {file.read((char*)&a[i], sizeof(int));}file.close();return 0;
}//
static void parse_string(char* line, std::string& image_name, std::vector<int>& rect)
{std::string str(line);rect.resize(0);int pos = str.find_first_of(" ");image_name = str.substr(0, pos);std::string str1 = str.substr(pos + 1, str.length());for (int i = 0; i < 4; ++i) {pos = str1.find_first_of(" ");std::string x = str1.substr(0, pos);str1 = str1.erase(0, pos+1);rect.push_back(std::stoi(x));}
}int test_fstream6()
{std::string name{ "E:/GitCode/Messy_Test/testdata/list.txt" };std::ifstream in(name.c_str(), std::ios::in);if (!in.is_open()) {fprintf(stderr, "open file fail: %s\n", name.c_str());return -1;}int count{ 0 };char line[256];in.getline(line, 256);count = atoi(line);std::cout << count << std::endl;//while (!in.eof()) {for (int i = 0; i < count; ++i) {in.getline(line, 256);std::cout << "line: "<< line << std::endl;std::string image_name{};std::vector<int> rect{};parse_string(line, image_name, rect);std::cout << "image name: " << image_name << std::endl;for (auto x : rect)std::cout << "  " << x << "  ";std::cout << std::endl;}in.close();return 0;
}//
int test_fstream7()
{std::string name{ "E:/GitCode/Messy_Test/testdata/list.txt" };std::ifstream in(name.c_str(), std::ios::in);if (!in.is_open()) {fprintf(stderr, "open file fail: %s\n", name.c_str());return -1;}int count{ 0 };std::string image_name{};int left{ 0 }, top{ 0 }, right{ 0 }, bottom{ 0 };in >> count;std::cout << "count: " << count << std::endl;for (int i = 0; i < count; ++i) {in >> image_name >> left >> top >> right >> bottom;fprintf(stdout, "image_name: %s, rect: %d, %d, %d, %d\n", image_name.c_str(), left, top, right, bottom);}in.close();return 0;
}


GitHub:https://github.com/fengbingchun/Messy_Test

相关文章:

浅谈Disruptor

Disruptor是一个低延迟(low-latency)&#xff0c;高吞吐量(high-throughput)的事件发布订阅框架。通过Disruptor&#xff0c;可以在一个JVM中发布事件&#xff0c;和订阅事件。相对于Java中的阻塞队列(ArrayBlockingQueue,LinkedBlockingQueue)&#xff0c;Disruptor的优点是性…

web 服务发布注意事项

1、在发布的时候首先查看服务器对外开放的端口&#xff0c;如果没有最好和客户进行沟通需要开放那些对应的端口&#xff0c;要不外界无法访问发布的站点。 2、在oracle需要远程控制服务器的数据库的时候需要开发1521端口。转载于:https://www.cnblogs.com/jzm53550629/p/337563…

OpenCV代码提取:resize函数的实现

之前在http://blog.csdn.net/fengbingchun/article/details/17335477 中有过对cv::resize函数五种插值算法的介绍。这里将OpenCV3.1中五种插值算法的代码进行了提取调整。支持N通道uchar和float类型。经测试&#xff0c;与OpenCV3.1结果完全一致。实现代码resize.hpp&#xff1…

IBM重磅开源Power芯片指令集?国产芯迎来新机遇?

整理 | 郭芮出品 | CSDN&#xff08;ID&#xff1a;CSDNnews&#xff09;自去年 IBM 以 340 亿美元收购了 Linux 巨头红帽之后&#xff0c;这家 107 岁的蓝色巨人终于又在开源方面有大动作了&#xff01;近日在 Linux 基金会开源峰会上&#xff0c;IBM 宣布向开源社区提供 Powe…

构造函数不能为虚/重载函数总结

构造函数不能为虚/重载函数总结 作为一个类&#xff0c;他最基础的成员函数就要数构造函数了。这里我们先探讨一下构造函数为什么不能是虚函数。 在解决这个问题之前&#xff0c;要先明白类中函数的调用方式。一个类的函数共用一个函数空间&#xff0c;因此在实例化的对象中是不…

通过data:image/png;base64把图片直接写在src里

2019独角兽企业重金招聘Python工程师标准>>> 关于用base64存储图片 网页上有些图片的src或css背景图片的url后面跟了一大串字符&#xff0c;比如&#xff1a;data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAEAAAAkCAYAAABIdFAMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZS…

算力“竞速”,企业AI落地的当务之急

充足的算力资源&#xff0c;在数据量持续增长及算法持续复杂化的前提下&#xff0c;无疑是保障人工智能应用落地效果的关键。软件定义算力——打造AI转型最佳实践8月2日&#xff0c;第四范式联合英特尔共同举办了AI实践者之声夏令营活动。第四范式基础架构负责人刘一鸣以《软件…

内存检测工具Dr. Memory的使用

Dr. Memory是一个内存调试工具&#xff0c;它是一个开源免费的内存检测工具&#xff0c;它能够及时发现内存相关的编程错误&#xff0c;比如未初始化访问、内存非法访问、数组越界读/写、以及内存泄露等。它可以在Linux、Windows、Mac OS和Android操作系统上使用。关于Dr. Memo…

手把手教你如何新建scrapy爬虫框架的第一个项目(下)

前几天小编带大家学会了如何在Scrapy框架下创建属于自己的第一个爬虫项目&#xff08;上&#xff09;&#xff0c;今天我们进一步深入的了解Scrapy爬虫项目创建&#xff0c;这里以伯乐在线网站的所有文章页为例进行说明。在我们创建好Scrapy爬虫项目之后&#xff0c;会得到上图…

.net完整的图文验证

摘自:http://blog.csdn.net/durongjian/article/details/4336380 一、创建ValidaeCode类库工程&#xff1a; 1、创建ValidaeCode类库工程&#xff0c;在[解决胜方案资源管理器]面板中&#xff0c;右键单击[ValidateCode]节点&#xff0c;并选择[属性]命令。 2、单击[属性]命令&…

Tesseract-OCR 3.04在Windows7 vs2013上编译过程

从https://github.com/tesseract-ocr/tesseract下载最新源码,commit id: 86acff5, 2016.06.07. 里面有个vs2010目录&#xff0c;用vs2013打开tesseract.sln。Tesseract依赖图像库Leptonica&#xff0c;Leptonica的编译过程可以参考http://blog.csdn.net/fengbingchun/article/d…

【Laravel-海贼王系列】第九章, Events 功能解析

Events 注册 框架如何在启动的时候加载注册的事件?框架如何触发事件?1&#xff0c;先在容器中注册 events 的全局对象。 Application 构造函数中对 events 进行注册代码 protected function registerBaseServiceProviders(){$this->register(new EventServiceProvider($th…

触类旁通,经典面试题最长公共子序列应该这么答

作者 | labuladong来源 | labuladong&#xff08;ID:labuladong)【导读】最长公共子序列&#xff08;Longest Common Subsequence&#xff0c;简称 LCS&#xff09;是一道非常经典的面试题目&#xff0c;因为它的解法是典型的二维动态规划&#xff0c;大部分比较困难的字符串问…

两分公支的IPSec***流量走总部测试

一.概述&#xff1a;在论坛上看到一个朋友发帖希望两个分支的IPSEC ***流量经过总部&#xff0c;如是搭建拓扑测试了一下&#xff0c;因为跑两个VM版的ASA8.42机器性能不过&#xff0c;所以用PIX8.0来代替ASA,应该主要配置都跟ASA8.0差不多。二.基本思路&#xff1a;A.两个分支…

OpenCV代码提取:cvtColor函数的实现

OpenCV中的cvtColor函数包括了很多颜色格式之间的转换&#xff0c;用起来很方便&#xff0c;这里对cvtColor函数的code进行了提取&#xff0c;经测试&#xff0c;和OpenCV3.1结果完全一致。实现代码cvtColor.hpp:// fbc_cv is free software and uses the same licence as Open…

关于java.util.LinkedHashMap cannot be cast to ......的解决办法

今天在项目中遇到一个问题&#xff0c;接口接收到list在对list进行遍历的时候报出如下错误: 断点看一下这个list感觉没有任何的问题: 那为什么会报这个错误呢 这个接口是这样的&#xff0c;在想会不会是json在转list的时候把这个list给整坏了。 于是&#xff0c;我把这个list再…

三两下实现NLP训练和预测,这四个框架你要知道

作者 | 狄东林 刘元兴 朱庆福 胡景雯编辑 | 刘元兴&#xff0c;崔一鸣来源 | 哈工大SCIR&#xff08;ID:HIT_SCIR)引言随着人工智能的发展&#xff0c;越来越多深度学习框架如雨后春笋般涌现&#xff0c;例如PyTorch、TensorFlow、Keras、MXNet、Theano 和 PaddlePaddle 等。这…

大学计算机基础实验

下载2013算法实验报告.rar转载于:https://www.cnblogs.com/shajianheng/p/3381968.html

java基础(十三)-----详解内部类——Java高级开发必须懂的

java基础(十三)-----详解内部类——Java高级开发必须懂的 目录 为什么要使用内部类内部类基础静态内部类 成员内部类 成员内部类的对象创建继承成员内部类局部内部类推荐博客匿名内部类正文 可以将一个类的定义放在另一个类的定义内部&#xff0c;这就是内部类。 回到顶部为什么…

C++中函数指针的使用

A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.函数指针是一个指向函数的指针,函数指针表示一个函数的入口地址。指针是变量&…

只做好CTR预估远不够,淘宝融合CTR、GMV、收入等多目标有绝招

作者 | 吴海波转载自知乎用户吴海波【导读】一直以来&#xff0c;电商场景就存在 ctr、cvr、gmv、成交 uv 等多个目标&#xff0c;都是核心指标。理想情况下&#xff0c;提升 ctr 就能提升 gmv&#xff0c;但本文作者认为&#xff0c;在一定程度上&#xff0c; ctr 和 gmv 并不…

Android监听HOME按键

2019独角兽企业重金招聘Python工程师标准>>> <!-- lang: java --> class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {static final String SYSTEM_REASON "reason";static final String SYSTEM_HOME_KEY "homekey";// …

OpenCV代码提取:merge/split函数的实现

对OpenCV中的merge/split函数进行了实现&#xff0c;经测试&#xff0c;与OpenCV3.1结果完全一致。merge实现代码merge.hpp&#xff1a;// fbc_cv is free software and uses the same licence as OpenCV // Email: fengbingchun163.com#ifndef FBC_CV_MERGE_HPP_ #define FBC_…

DeepMind提图像生成的递归神经网络DRAW,158行Python代码复现

作者 | Samuel Noriega译者 | Freesia编辑 | 夕颜出品 | AI科技大本营&#xff08;ID: rgznai100&#xff09;【导读】最近&#xff0c;谷歌 DeepMInd 发表论文( DRAW: A Recurrent Neural Network For Image Generation&#xff09;&#xff0c;提出了一个用于图像生成的递归神…

其他进制的数字

JS中如果需要表示16进制的数字,则需要以0X开头 0X10 八进制数字以0开头 070 070有些浏览器会以8进制解析,但是有些则用10进制解析,10进制为70,8进制为56 所以parseint() 第二个参数可以设定进制,比如 parseint(“070”,10)代表以10进制解析070 2进制以0b开头,但是不是所有浏览…

java中的移位运算符

移位运算符是在数字的二进制形式上进行平移。主要有左移&#xff08;<<&#xff09;、带符号右移&#xff08;>>&#xff09;以及无符号右移&#xff08;>>>&#xff09;。左移运算符&#xff08;<<&#xff09;的运算规则为&#xff1a;按二进制形…

C++11中nullptr的使用

在C语言中&#xff0c;NULL实际上是一个void* 的指针&#xff0c;然后把void* 指针赋值给其它类型的指针的时候&#xff0c;会隐式转换成相应的类型。而如果用一个C编译器来编译的时候是要出错的&#xff0c;因为C是强类型的&#xff0c;void* 是不能隐式转换成其它指针类型的。…

埃森哲、亚马逊和万事达卡抱团推出的区块链项目有何神通?

据外媒报道&#xff0c;今日埃森哲宣布了一项新的区块链项目&#xff0c;该项目为基于区块链的循环供应链&#xff0c;将与万事达卡和亚马逊共同合作。据官方介绍&#xff0c;这个基于区块链的循环供应链能够让客户识别供应链上的小规模供应商和种植者&#xff0c;例如&#xf…

小团队如何玩转物联网开发?

近几年来&#xff0c;物联网发展迅速&#xff1a;据中商产业研究院《2016——2021年中国物联网产业市场研究报告》显示&#xff0c;预计到2020年&#xff0c;中国物联网的整体规模将达2.2万亿元&#xff0c;产业规模比互联网大30倍。与之相反的是&#xff0c;物联网开发者在开发…

Build Boost C++ libraries for x32/x64 VC++ compilers on Windows

2019独角兽企业重金招聘Python工程师标准>>> Boost is a set of libraries for the C programming language that provide support for tasks and structures such as linear algebra, pseudorandom number generation, multithreading, image processing, regular …