C++学习笔记:对文件流的写入和读取
2016-07-12 16:29
447 查看
前言
c++对文件的读取写入,最简单的是利用下面三个类。名称 | 描述 |
---|---|
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. |
ofstream建立和写入文件
建立一个名为 test.txt 的文档,写入数据的方式多种。#include<iostream> #include<fstream> using namespace std; int main() { ofstream ofs("test.txt"); if ( !ofs.is_open() ) { cout << "failed" << endl; return 0; } ofs << "hello world!" << endl; //直接写入 int a = 10086; ofs << a << endl; //间接写入 string s = "welcome!"; ofs << s.c_str() << "\t" << a << endl; //不同格式混合写入 string ss = "this is a test for ofstream!\n"; ofs.write(ss.c_str() , ss.length()); //利用write方法 ofs.close(); system("pause"); }
ifstream读取文件
从 test.txt 文档中读取数据,可以使用不同的数据类型来读取,过程都大同小异。#include<iostream> #include<fstream> #include<sstream> using namespace std; int main() { ifstream ifs; ifs.open("test.txt" , ios::in); if ( !ifs ) { cout << "no such file" << endl; return 0; } cout << "\n**********stringbuf**********\n" << endl; string str; stringbuf *sb = new stringbuf(); while ( !ifs.eof() ) { ifs >> sb; cout << sb; str.append(sb->str()); } cout << "\n**********stringbuf to string**********\n" << endl; cout << str; cout << "\n**********char**********\n" << endl; ifs.seekg(0 , ifs.beg); //当前坐标要归零 char cc; while ( !ifs.eof() ) { ifs.get(cc); cout << cc; } ifs.close(); system("pause"); }
最后结果
fstream对文件读写操作
fstream可以说是上面两个的综合,不过个人建议,还是用上面两个类,编程的时候便于区分。#include<iostream> #include<fstream> using namespace std; int main() { fstream fs("test2.txt" , ios::out); //创建文件 if ( !fs.is_open() ) { cout << "failed" << endl; return 0; } fs << "test2" << endl; //写入数据 fs.close(); fs.open("test2.txt" , ios::in); //读取文件 if ( !fs.is_open() ) { cout << "no such file" << endl; return 0; } char c; while ( !fs.eof() ) { fs.get(c); cout << c; } fs.close(); system("pause"); }
相关文章推荐
- 基于C++11的线程池
- control may reach end of non-void function [-Werror,-Wreturn-type] 错误记录
- C++中Vector保存 原始指针和智能指针的析构问题
- C++类的静态成员初始化详细讲解
- VC 工程中包含 .c 或cpp文件编译时产生的.pch预编译头错误(C1853)
- 《C++ Primer Plus》第12章 类和动态内存分配 学习笔记
- C语言 二叉树的链式存储实例
- Leetcode 206. Reverse Linked List (Easy) (cpp)
- Effective Modern C++ 笔记(1):模板类型推导
- 控件响应鼠标操作事件中,判断IsIdle()作用
- 直接型FIR滤波器的C语言实现
- 借助编译器阅读耗子叔6个变态的C语言Hello World程序
- 设计模式之模板方法模式(C++)
- C语言学习笔记字符读入读出
- 趣味100道C语言程序题num three
- Counting Sort
- C++ 邦德市
- C语言入门(十九)指针函数和函数指针
- BZOJ - 1977 [BeiJing2010组队]次小生成树 Tree Kruskal演算法+最近公共祖先
- C++虚函数,纯虚函数,抽象类