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. SQL语句的执行计划(oracle表的三种链接方式)

    SQL语句我们写完之后,就是分析其优化,这就要求我们了解到底数据是怎么存储. 首先我们需要了解,表链接的几种方式 nested loop join sort merge join hash join ...

  2. 十步让 WebForm项目 变为 Mvc项目

    1.创建一个项目名为 App_Asp 的 Asp.NET 空 Web 应用程序2.添加全局应用程序类 Global.asax3.富文本打开 Global,修改 Inherits 为 App_Asp_G ...

  3. Android——Dialog

    public class DialogActivity extends Activity { //进度对话框    ProgressDialog progressDialog; @Override   ...

  4. Appium输入中文的问题,简单的方法

    经常有人问,Appium怎么输入中文,下面提供一种相对简单的方式. 以前曾经提到过capabilities关键字,里面有这样2个属性, |`unicodeKeyboard`| 使用 Unicode 输 ...

  5. 腾讯校招技术岗面试经历及总结(已发offer)

    关于笔试:只要前期复习到位,笔试还是很好过的,但是当然 分数 越高越好,否则后面会被面试官鄙视的.题目可能难度较大,但是要把会做的 都做 对,如果时间比较紧可以适度放弃部分不会的题目. 关于面试: 温 ...

  6. ASPXGridView用法

    一.ASPXGridView外观显示 属性: Caption----列的标题( KeyFieldName----数据库字段 SEOFriendly 是否启用搜索引擎优化 Summary 指定分页汇总信 ...

  7. java中反射

    Person.java===>>person.class ==>>jvm中的类加载器===>>class对象:代表内存中Person.class ==>> ...

  8. spring注解 构造函数问题

    因为类首先被Spring实例化的时候,会调用构造函数.只有实例化后,才会注入.你等于没注入就调用了,所以报错. 把DAO实现类注入到service实现类中,把service的接口(注意不要是servi ...

  9. JavaScript 性能优化1

    一直在学习javascript,也有看过<犀利开发Jquery内核详解与实践>,对这本书的评价只有两个字犀利,可能是对javascript理解的还不够透彻异或是自己太笨,更多的是自己不擅于 ...

  10. Sunglasses

    It's hot this summer. It also reminds me of one case about sunglasses. She was new to this company a ...