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++文件操作(输入输出、格式控制、文件打开模式、测试流状态、二进制读写)的更多相关文章

  1. 打开Excel时提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致"

    问题描述:     系统安装了WPS时,Analyzer导出excel时候,会提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致",这是Excel的安全问题,   ...

  2. 【原创】打开Excel时提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致"

    问题描述:     系统安装了WPS时,Analyzer导出excel时候,会提示"您尝试打开的文件**.xls的格式与文件扩展名指定的格式不一致",这是Excel的安全问题,   ...

  3. matlab文件操作及读txt文件(fopen,fseek,fread,fclose)

    文件操作是一种重要的输入输出方式,即从数据文件读取数据或将结果写入数据文件.MATLAB提供了一系列低层输入输出函数,专门用于文件操作. 1.文件的打开与关闭 1)打开文件 在读写文件之前,必须先用f ...

  4. MATLAB文件操作及读txt文件

    转自:http://blog.csdn.net/vblittleboy/article/details/8049748 文件操作是一种重要的输入输出方式,即从数据文件读取数据或将结果写入数据文件.MA ...

  5. 表空间tablespace,数据文件datafiles,和控制文件control files介绍

    https://docs.oracle.com/cd/B19306_01/server.102/b14220/physical.htm#i5919 本文系翻译 表空间tablespace,数据文件da ...

  6. 重新想象 Windows 8 Store Apps (24) - 文件系统: Application Data 中的文件操作, Package 中的文件操作, 可移动存储中的文件操作

    原文:重新想象 Windows 8 Store Apps (24) - 文件系统: Application Data 中的文件操作, Package 中的文件操作, 可移动存储中的文件操作 [源码下载 ...

  7. PHP文件操作 之读取一个文件(以二进制只读的方式打开)

    最近应用了文件的读取,顺便复习一下! //读取一个文件 $f = fopen($filename,'rb'); $f: 表示返回的一个资源句柄 $filename:要打开的文件路径 rb:参数,表示只 ...

  8. 掌握Git撤销操作,随心所欲控制文件状态

    本文主要讨论和撤销有关的 git 操作.目的是让读者在遇到关于撤销问题时能够方便迅速对照执行解决问题,而不用去翻阅参数繁多的 git 使用说明. 一开始你只需了解大致功能即可,不必记住所有命令和具体参 ...

  9. 文件操作(FILE)与常用文件操作函数

    文件 1.文件基本概念 C程序把文件分为ASCII文件和二进制文件,ASCII文件又称文本文件,二进制文件和文本文件(也称ASCII码文件)二进制文件中,数值型数据是以二进制形式存储的, 而在文本文件 ...

随机推荐

  1. vc 递归删除非空文件夹

    我觉得这是一个非常不错的递归例子 头文件 #pragma once #include <atlstr.h> #include <io.h> #include <strin ...

  2. OSChina中远程GIT仓库同步探索

    GIT平台在OSChina中的搭建帮了我们很大的忙,但如何将本地GIT仓库上传至OSChina的远程仓库,相信这是一个艰难的坎,今天我就在此总结我的成功经验,帮助大家,共同学习.由于条件有限,我全部的 ...

  3. 消费者端的Spring JMS 连接ActiveMQ接收生产者Oozie Server发送的Oozie作业执行结果

    一,介绍 Oozie是一个Hadoop工作流服务器,接收Client提交的作业(MapReduce作业)请求,并把该作业提交给MapReduce执行.同时,Oozie还可以实现消息通知功能,只要配置好 ...

  4. Operator overloading

    By defining other special methods, you can specify the behavior of operators on user-defined types. ...

  5. ApplePay

    ApplePay要在项目有里配置,,配置好项目之后,就剩下编码了,做ApplePay首先要检查设备是否支持ApplePay,支持 ApplePay的设备在 iPhone6及以后,  PKPayment ...

  6. 学习资料 数据查询语言DQL

    数据查询语言DQL介绍及其应用: 查询是SQL语言的核心,SQL语言只提供唯一一个用于数据库查询的语句,即SELECT语句.用于表达SQL查询的SELECT语句是功能最强也是最复杂的SQL语句,它提供 ...

  7. jquery学习记录

    1.选择器实例 语法 描述 $(this) 当前 HTML 元素 $("p") 所有 <p> 元素 $("p.intro") 所有 class=&q ...

  8. 网络资源管理系统LANsurveyor实战体验

    网络资源管理系统LANsurveyor实战体验 用于生成网络拓扑并管理网络各种设备的软件很多(例如上一篇文章展示的CiscoWorks 2000,我还介绍过开源领域的Cheops-NG),今天为大家介 ...

  9. sql server安装程序无法验证服务账户是什么原因

    为了帮助网友解决“sql server安装程序无法验证服务”相关的问题,中国学网通过互联网对“sql server安装程序无法验证服务”相关的解决方案进行了整理,用户详细问题包括:能是尚未向所有要安装 ...

  10. RAW格式

    一.什么是RAW文件?RAW文件主要是一种记录了数码相机传感器的原始信息,同时伴随着一些由相机所产生的一些元数据(metadata,诸如IS0的设置.快门速度.光圈值.白平衡等)的文件.不同的相机制造 ...