C++文件操作(输入输出、格式控制、文件打开模式、测试流状态、二进制读写)
1.向文件写数据
头文件#include <ofstream>
①Create an instance of ofstream(创建ofstream实例)
②Open the file with open() or ofstreamconstructor (用open()或者构造函数打开文件)
③Writedata to the file with "<<" (用流插入运算符写数据)
④Close the file (explicitly close()) (显式地使用close()函数关闭文件)
若文件已存在,内容被直接清除。
#include <iostream>
#include <fstream>
using namespace std; int main()
{
// ofstream output("score.txt"); 构造函数打开文件
ofstream output;
//创建文件
output.open("score.txt");
//写数据 output 类似于cout
output << "daidai" << " " << << endl;
//关闭文件
output.close();
return ;
}

2.从文件读数据
头文件#include <ifstream>
①Create an instance of ifstream(创建ifstream对象)
②Open the file (use open() or ifstreamconstructor) (用open()函数或构造函数打开文件)
③Read data from the file with ">>" (用流提取运算符从文件读数据)
④Close the file (explicitly using close() ) (显式调用close()函数关闭文件)
#include <iostream>
#include <fstream>
using namespace std; int main()
{
// ofstream output("score.txt"); 构造函数打开文件
ifstream input;
//打开文件
input.open("score.txt");
//读数据 input
char name[];
int score;
input >> name >> score;
cout << name << " " << score << endl;
//关闭文件
input.close();
return ;
}

3.格式控制
头文件#include <iomanip>
①setw(width) 设置域宽
setw()控制符只对其后输出的第一个数据有效,其他控制符则对其后的所有输入输出产生影响。
默认为setw(0),按实际输出。
如果输出的数值占用的宽度超过setw(int n)设置的宽度,则按实际宽度输出。
Eg: cout<<setw(5)<<'a'<<'b'<<endl; 输出: ab
float f=0.12345; cout<<setw(3)<<f<<endl; 输出为0.12345
②setfill(c)
设置填充字符,即“<<"符号后面的数据长度小于域宽时,使用什么字符进行填充。
Eg: cout<<setfill('*')<<setw(5)<<'a'<<endl; 输出:****a
③setprecision(int n)
可以控制显示浮点数的有效位
n代表数字总位数

setprecision(0)的效果取决于编译器。不同编译器的实现是不同的。
本例中:
VC++2013输出:2.42857
Dev C++ 5.6.0 (MinGW GCC 4.8.1)输出: 2
④showpoint
将浮点数以带小数点、带结尾0 的形式输出,即便它没有小数部分
Eg:
float f1 = 13;
float f2 = 3.1415926;
float f3 = 5;
cout << showpoint << f1 << endl;
cout << showpoint << f2 << " " << f3 <<endl;
输出:13.0000
3.14159 5.00000
⑤left 输出内容左对齐
right 输出内容右对齐
Eg:
cout << setw(5) << 13 << endl;
cout << setw(5) << right << 13 << endl;
cout << setw(5) << left << 13 << endl;
输出: 13
13
13
⑥getline
getline(chararray[], intsize, chardelimitChar) //要写入的数组,大小,分隔符
因为 >>运算符要求数据用空格分隔
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream input("state.txt");
char name[];
input >> name;
cout << name << endl;
return ;
}
与预期不同。
//运用getline
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream input("state.txt");
char name[];
while(!input.eof()){ // Continue if not end of file
input.getline(name,,'#');
cout << name << endl;
}
return ;
}

⑦ get: read a character
put:write a character
//copy get put
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
cout << "Enter a source file name:";
char inputFilename[];
cin >> inputFilename; cout << "Enter a target file name:";
char outputFilename[];
cin >> outputFilename; ifstream input(inputFilename);
ofstream output(outputFilename); while( !input.eof() ) { //Continue if not end of file
output.put(input.get());
} input.close();
output.close();
cout << "\nCopy Done" << endl;
return ;
}


4.文件打开模式
fstream= ofstream+ ifstream
ofstream: write data
ifstream: read data
Mode Description
ios::in Opens a file for input. 读模式
ios::out Opens a file for output. 写模式
ios::app Appends all output to the end of the file. 追加模式
ios::ate Opens a file for output. If the file already exists, move to the end of the file. Data can be written anywhere in the file.
打开文件用于输出。若文件存在则光标移至文件尾部。数据可以在任意位置写入
ios::truct Discards the file’s contents if the file already exists. (This is the default action for ios:out).
若文件存在则丢弃其内容,这是ios:out的默认方式
ios::binary Opens a file for binary input and output.打开文件以二进制模式读写
模式组合: |
Eg:stream.open("state.txt", ios::out | ios::app);
5.测试流状态
流状态位 (Stream State Bit):These bit values (0or 1) indicate the state of a stream. (比特值指示流的当前状态)
Bit When to set
ios::eofbit Set when the end of an input stream is reached. 到达文件末尾时
ios::failbit Set when an operation failed. 操作失败时
ios::hardfail Set when an unrecoverable error occurred. 遇到不可恢复的错误时
ios::badbit Set when an invalid operation has been attempted. 试图进行非法操作时
ios::goodbit Set when an operation is successful. 操作成功时
流状态函数(Stream State Functions)
Function Description
eof() Returns true if the eofbit flag is set.
fail() Returns true if the failbit or hardfail flags is set.
bad() Returns true if the badbit is set.
good() Returns true if the goodbit is set.
clear() Clears all flags.
6.二进制读写
文本文件与二进制文件,都按二进制格式存储比特序列
text file : interpretedas a sequence of characters (解释为一系列字符)
binary file : interpretedas a sequence of bits. (解释为一系列比特)
Eg: the decimal integer 199 (对于十进制整数199)
in text file: as the sequence of three characters, '1', '9', '9', (在文本文件中存为3个字符),stores as 3 bytes: 0x31, 0x39, 0x39 (三个字符的ASCII码)
in bin file: as a byte-type value C7(decimal 199= hex C7 (在二进制文件中存为C7),stores as 1 bytes: 0xC7
ios::binary以二进制模式打开文件
文本模式读写函数
write: <<operator; put()
read : >>operator; get(); getline()
二进制模式读写函数
write: write(); streamObject.write(char* address, intsize)
read : read(); streamObject.read(char * address, intsize)
将任意类型数据写入文件:转换为字节流,write进去。
reinterpret_cast<dataType>(address) //将数据的地址转换为为字符类型指针用于二进制读写
Eg:streamObject.write(reinterpret_cast<char *>, intsize);
char s[10]; streamObject.read(s, intsize);
int value; streamObject.read(reinterpret_cast<char*>(&value), sizeof(value));
double array[] = {1.1,2.2,3.3} streamObject.write(reinterpret_cast<char*>(array), sizeof(array));
Student stu1("kuotian",20,'f'), stu2;
streamObject.write(reinterpret_cast<char*>(&stu1), sizeof(Student));
streamObject.read(reinterpret_cast<char*>(&stu2), sizeof(Student));
7.
seekp, seekg, tellp, tellg
seek: 移动文件指针
tell:获取文件指针位置
p: put,表示操作输出文件中的指针
g: get,表示操作输入文件中的指针
Seek Base Description
ios::beg Calculates the offset from the beginning of the file.
ios::end Calculates the offset from the end of the file.
ios::cur Calculates the offset from the current file pointer.
Statement Description
seekg(100L, ios::beg); Moves the file pointer to the 100th byte from the beginning of the file.
seekg(-100L, ios::end); Moves the file pointer to the 100th byte backward from the end of the file.
seekp(42L, ios::cur); Moves the file pointer to the 42nd byte forward from the current file pointer.
seekp(-42L, ios::cur); Moves the file pointer to the 42nd byte backward from the current file pointer.
seekp(100L); Moves the file pointer to the 100th byte in the file.
C++文件操作(输入输出、格式控制、文件打开模式、测试流状态、二进制读写)的更多相关文章
- 打开Excel时提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致"
问题描述: 系统安装了WPS时,Analyzer导出excel时候,会提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致",这是Excel的安全问题, ...
- 【原创】打开Excel时提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致"
问题描述: 系统安装了WPS时,Analyzer导出excel时候,会提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致",这是Excel的安全问题, ...
- matlab文件操作及读txt文件(fopen,fseek,fread,fclose)
文件操作是一种重要的输入输出方式,即从数据文件读取数据或将结果写入数据文件.MATLAB提供了一系列低层输入输出函数,专门用于文件操作. 1.文件的打开与关闭 1)打开文件 在读写文件之前,必须先用f ...
- MATLAB文件操作及读txt文件
转自:http://blog.csdn.net/vblittleboy/article/details/8049748 文件操作是一种重要的输入输出方式,即从数据文件读取数据或将结果写入数据文件.MA ...
- 表空间tablespace,数据文件datafiles,和控制文件control files介绍
https://docs.oracle.com/cd/B19306_01/server.102/b14220/physical.htm#i5919 本文系翻译 表空间tablespace,数据文件da ...
- 重新想象 Windows 8 Store Apps (24) - 文件系统: Application Data 中的文件操作, Package 中的文件操作, 可移动存储中的文件操作
原文:重新想象 Windows 8 Store Apps (24) - 文件系统: Application Data 中的文件操作, Package 中的文件操作, 可移动存储中的文件操作 [源码下载 ...
- PHP文件操作 之读取一个文件(以二进制只读的方式打开)
最近应用了文件的读取,顺便复习一下! //读取一个文件 $f = fopen($filename,'rb'); $f: 表示返回的一个资源句柄 $filename:要打开的文件路径 rb:参数,表示只 ...
- 掌握Git撤销操作,随心所欲控制文件状态
本文主要讨论和撤销有关的 git 操作.目的是让读者在遇到关于撤销问题时能够方便迅速对照执行解决问题,而不用去翻阅参数繁多的 git 使用说明. 一开始你只需了解大致功能即可,不必记住所有命令和具体参 ...
- 文件操作(FILE)与常用文件操作函数
文件 1.文件基本概念 C程序把文件分为ASCII文件和二进制文件,ASCII文件又称文本文件,二进制文件和文本文件(也称ASCII码文件)二进制文件中,数值型数据是以二进制形式存储的, 而在文本文件 ...
随机推荐
- 初探接口测试框架--python系列4
点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...
- LibreOffice源码编译以及生成VS项目
最权威的社区链接:https://wiki.documentfoundation.org/Development/BuildingOnWindows 也许英文好的人直接看wiki上的说明就能很容易的编 ...
- 【练习】手工生成awr报告
①首先进入$ORACLE_HOME/rdbms/admin目录 [oracle@host02 ~]$ cd $ORACLE_HOME/rdbms/admin 该目录下 [oracle@host02 a ...
- NOIP1998 拼数
http://www.luogu.org/problem/show?pid=1012 题目描述 设有n个正整数(n≤20),将它们联接成一排,组成一个最大的多位整数. 例如:n=3时,3个整数13,3 ...
- 学习总结 java 输入输出流
思维导图 代码实际演示 package com.hanqi.io; import java.io.*; public class Test1 { public static void main(Str ...
- 洛谷P2723 丑数 Humble Numbers
P2723 丑数 Humble Numbers 52通过 138提交 题目提供者该用户不存在 标签USACO 难度普及/提高- 提交 讨论 题解 最新讨论 暂时没有讨论 题目背景 对于一给定的素数 ...
- 如何利用百度地图JSAPI画带箭头的线?
百度地图JSAPI提供两种绘制多折线的方式,一种是已知多折线经纬度坐标串通过AddOverlay接口进行添加:另一种是通过在地图上鼠标单击进行绘制(鼠标绘制工具条库).目前这两种方式只能绘制多折线,并 ...
- 如何在MAC机器中实现移动设备WiFI上网(没有专门的无线路由器的情况)
在很多办公室甚至家中都有无线路由器以方便通过WIFI信号上网.如果没有无线路由器,如何让多个移动智能终端同时上网呢?如果你是Windows用户那么可以选择wifi共享精灵来解决,如果你拥有MAC机器, ...
- extern “C”调用测试与验证-2016.01.06
1 调用情形说明 在上一篇关于extern “c”原理以及用法中,详细的说明了为什么需要extern “c”以及如何使用它解决c与c++混合编程时遇到的问题.接下来,使用示例验证方式验证c与c++函数 ...
- infusion度量金字塔数据解释
inFusion能够探测超过20中代码味道和代码缺陷,包括重复代码,破坏封装的类(如数据类或者万能类),高耦合的方法和类,以及一些设计不合理的类继承结构.当我们使用inFusion工具分析代码时,在分 ...