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

C++中fstream的使用相关推荐

  1. C++中fstream

    #include <fstream> 头文件fstream包含了ifstream.ofstream.fstream三个类,可以通过定义这三个类的对象来实现相对应的文件操作. #includ ...

  2. C++中fstream 的使用一

    1. stream(流),流是一种抽象,它负责在数据的产生者和数据的消费者之间建立联系,并管理数据的流动. 头文件<fstream>是关于文件输入输出流的,是管理文件流的.在C++中对于文 ...

  3. C++中fstream的用法

    一 stream类 fstream顾名思义就是文件流,所以它也是以stream类为基础的.stream类有两个重要的运算符: 1.插入器(<<) 向流输出数据.比如: cout<&l ...

  4. 解决:VS 2005/2008 中 fstream 不能处理带有中文路径的问题

    转自:http://blog.csdn.net/code_robot/archive/2010/06/23/5688867.aspx 有时候用ifstream或ofstream打开带有中文路径的文件会 ...

  5. C++中的fstream/ifstream/ofstream和MFC中的CFile/CStdioFile

    在看C++编程思想中,每个练习基本都是使用ofstream,ifstream,fstream,以前粗略知道其用法和含义,在看了几位大牛的博文后,进行整理和总结: 这里主要是讨论fstream的内容: ...

  6. C++中的文件读写操作(1)

    #include "iostream" #include "fstream" #include "vector" #include &quo ...

  7. C++文件读写详解(ofstream,ifstream,fstream)

    在看C++编程思想中,每个练习基本都是使用ofstream,ifstream,fstream,以前粗略知道其用法和含义,在看了几位大牛的博文后,进行整理和总结: 这里主要是讨论fstream的内容: ...

  8. C++读取txt数据为二维数组 将数据保存到txt文本中

      C++读取txt数据为二维数组 保存txt文本数据     C++文件读写操作有:ofstream,ifstream,fstream: #include <fstream> ofstr ...

  9. 【C/C++】fstream详解

    一.概述 C中对文件的操作是通过 FILE文件指针 和相关关函数来实现的. C++中是通过 fstream文件流 来实现的,其包含 ifstream.ofstream.fstream 三个类,通过定义 ...

最新文章

  1. 【 C 】用动态数组实现堆栈
  2. SPQuery 查询知多少
  3. Pyhton 随机数的使用
  4. 如何使用自定义端口运行 Flutter Web
  5. 模板(Template)
  6. 笔记-网页内嵌Google地图与地理位置模拟
  7. Intel 11代全新核显出现了!好强 好乱
  8. python语言应用章节答案_智慧树APPPython语言应用第十单元章节测试答案
  9. 项目管理修炼之道-读书流水
  10. 多线程-线程间通信-多生产者多消费者示例
  11. sql server 2005 使用Log Explorer查看和恢复数据
  12. CASE WHEN 及 SELECT CASE WHEN的用法
  13. 软文推广标题的写法,怎么才能让软文标题更有吸引力
  14. idea toggle offline mode
  15. 笔试题:输入0123456789对应输出“一二三四五六七八九”
  16. 在函数前面加上WINAPI、CALLBACK等是什么意思
  17. 【javase系列基础包装类及日历类详细总结,看完不会来找我~】
  18. 显著性检测学习笔记(2):DMRA__2019_ICCV
  19. graphpad图片怎么导出矢量图_Graphpad Prism 8如何绘制生存曲线
  20. 正式宣布,小米10在高端市场碾压华为,夺下电商平台销量第一名

热门文章

  1. C指针5:字符串指针(指向字符串的指针)
  2. 基于RFID的防伪系统设计
  3. SVM进行手写数字识别
  4. Linux那些事儿之我是Sysfs(5)举例二sculld
  5. 深度学习--TensorFlow(5)BP神经网络(混淆矩阵、准确率、精确率、召回率、F值)
  6. jupyter分割代码块_科研分享—Python根据关键词自动抓取Pubmed文献标题(附全部代码)文末有福利...
  7. 机器学习与高维信息检索 - Note 2 - 统计决策和机器学习
  8. 【某小学生作文】《我的爸爸是名驾驶员》
  9. CSS自定义鼠标样式。JS获取鼠标坐标,实现提示气泡框跟随鼠标移动
  10. JAVA获取局域网内对应IP电脑的MAC地址(物理地址)