1、共同的打开文件方式:

fin.open("test.txt",ios::binary)
fout.open("test.txt",ios::binary)
fboth.open("test.txt",ios::in|ios::out|ios::binary)
或者
fistream fin("test.txt",ios::binary)
fostream fout("test.txt",ios::binary)
fstream fboth("test.txt",ios::in|ios::out|ios::binary)

二进制文件的读写
第一种方式:使用函数get和put
1.例如 fout.put(ch)
fin.get(ch)

//练习1 将a到z的26个字符写到E:\\C++\\file2.txt中,并读取出来

#include<iostream>
#include<fstream>
using namespace std; //往文件写入数据
void filefout()
{
//ofstream fout("E:\\C++\\file2.txt",ios::binary);
ofstream fout;
fout.open("E:\\C++\\file2.txt",ios::binary);
if(!fout)
{
cout<<"the write file can not open";
exit();
}
char ch='a';
for(int i=;i<;i++)
{
fout.put(ch);
ch++;
}
fout.close();
} //从文件读取数据
void filefin()
{
ifstream fin;
fin.open("E:\\C++\\file2.txt",ios::binary);
if(!fin)
{
cout<<"the read file can not open";
exit();
}
char ch; while(fin.get(ch))
cout<<ch;
/*
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
*/
fin.close();
cout<<endl;
} int main()
{
filefout();
filefin();
return ;
}
/*
abcdefghijklmnopqrstuvwxyz
*/

第二种方式:使用read函数和write函数 
2.例如 fin.read(char*buf,int len)
fout.write(char*buf,int len)

练习2:将两门课程名和成绩以二进制的形式存储在E:\\C++\\file3.txt中,并读取出来

#include<iostream>
#include<fstream>
using namespace std;
struct list
{
char course[];
int score;
}; //往文件中写入数据
void filewrite()
{
list list[]={"Computer",,"Math",};
ofstream fout("E:\\C++\\file3.txt",ios::binary);
if(!fout)
{
cout<<"The write file can not open!\n";
abort();//exit(1)
}
for(int i=;i<;i++)
{
fout.write((char*)&list[i],sizeof(list[i]));
}
fout.close();
} //从文件读取数据
void fileread()
{
list list[];
ifstream fin("E:\\C++\\file3.txt",ios::binary);
if(!fin)
{
cout<<"The read file can not open!\n";
exit();
}
for(int i=;i<;i++)
{
fin.read((char*)&list,sizeof(list[i]));
cout<<list[i].course<<" "<<list[i].score<<endl;;
}
fin.close();
} int main()
{
filewrite();
fileread();
return ;
}
/*
Computer 90
Math 78
请按任意键继续. . .
*/

2、在头文件fstream.h中:
类名 说明 功能
ifstream 输入文件流类 用于文件的输入
ofstream 输出文件流类 用于文件的输出
fstream 输入输出流类 用于文件的输入/输出

建立流对象,例如
ifstream fin
ofstream fout
fstream fboth

打开文件方式有两种:
(1)使用成员函数open打开文件
文件流对象.open(文件名,打开模式)
例如:fin.open("test.txt",ios::in)===fin.open("test.txt")
fboth.open("test.txt",ios::in|ios::out|ios::binary)
打开模式例如:ios::in输入操作、ios::out输出操作、ios::binary二进制模式 输入输出模式一般会按流对象进行默认

(2)定义文件流对象时指定参数,通过调用文件流类的构造函数打开文件
例如:ofstream fout("test.txt").....

判断读写文件是否成功?
判断条件:文件打开失败,与文件相关联的流对象的值是0;否则是1.
例如:if(!fout)
{
      cout<<"Cannot open file!\n ";
      //return 1;
}

关闭文件:fout.close();

练习1:先建立一个输出文件,向它写入数据,然后关闭文件,在按输入模式打开它,并读取信息。

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//往文件写入数据
ofstream fout("E:\\C++\\file1.txt");//ofstream fout("E:\\C++\\file1.txt","ios:out");
if(!fout) //如果文件打开失败,fout返回0
{
cout<<"Cannot open file!\n ";
return ;
}
fout<<"Hello world!\n"; //将一个字符串写到文件中
fout<<<<' '<<hex<<<<endl; //将一个十进制的100,分别以十进制格式和二进制格式写到文件中 fout.close(); //关闭写入流 //从文件读取数据
ifstream fin("E:\\C++\\file1.txt"); //ifstream fin("E:\\C++\\file1.txt","ios::in")
if(!fin) //如果文件打开失败,fin返回0
{
cout<<"Cannot open file!\n ";
return ;
}
char buffer[]; //定义一个存储数据的字符数粗缓冲区
while(!fin.eof())
{
fin.getline(buffer,); //一行一行读取数据
cout<<buffer<<endl;
}
/*
while(!fin.eof())
{
cout<<ch;
fin.get(ch);
}
*/
fin.close(); //关闭读取流 return ;
}

3、

(1). 检测文件结束EOF(end of file) 采用文件流方式读取方式时,使用成员函数eof(),可以检测这个结束符。
如果该函数的返回值非0,表示到达文件尾;返回值为0,表示未到达文件末尾。
例如: ifstream fin;
       ....
if(!fin.eof()) //尚未到达文件末尾
{
       ...
}

或者
ifstream fin;
....
if(!fin) //尚未到达文件末尾
{
       ...
}

或者
这种方式最常用:while(fin.get(ch))
cout.put(ch);//cout<<ch<<endl;

(2).二进制文件的随机读取

类istream提供了3个成员函数来对读指针进行操作:
tellg() //返回输入文件读指针的当前位置
seekg(文件中位置) //将输入文件中读指针移动指定的位置
seekg(位移量,参照位置) //以参照位置为基准,移动若干字节

文件中位置和位移量都是long型整数,以字节为单位,
参照位置 ios::beg //从文件开头计算要移动的字节数
ios::cur //从文件指针的当前位置计算要移动的字节数
ios::end //从文件末尾指针要移动的字节数

例如 fin.seekg(-/+50,ios::cur) //从文件指针当前位置向前/向后移动50个字节

类ostream提供了3个成员函数来对写指针进行操作:
tellp() //返回输出文件写指针的当前位置
seekp(文件的位置) //将输出文件中写指针移动到指定的位置
seekp(位移量,参照位置) //以参照位置为基准移动的若干字节

练习:随机访问二进制数据文件
有3门课程的数据,要求:
(1)以读写方式打开一个磁盘文件,并把这些数据存储到磁盘文件E:\\C++\\file4.txt;
(2)将文件指针定位到第3门课程,读取第3门课程的数据并显示出来;
(3)将文件指针定位到第1门课程,读取第1门课程的数据并显示出来;

#include<iostream>
#include<fstream>
using namespace std;
struct List
{
char course[];
int score;
};
int main()
{
List list[]={{"Computer",},{"Math",},{"Chinese",}};
List st;
fstream fboth;
fboth.open("E:\\C++\\file4.txt",ios::out|ios::in|ios::binary);
if(!fboth)
{
cout<<"The read-write file can not open!\n";
abort();
}
for(int i=;i<;i++)
{
fboth.write((char*)&list[i],sizeof(List));
}
//定位指针到第3门课程
fboth.seekg(sizeof(List)*);
fboth.read((char*)&st,sizeof(List));
cout<<st.course<<"\t"<<st.score<<endl; //定位指针到第1门课程
fboth.seekg(sizeof(List)*);
fboth.read((char*)&st,sizeof(List));
cout<<st.course<<"\t"<<st.score<<endl; //定位指针到下一门课程
fboth.seekg(sizeof(List)*,ios::cur);
fboth.read((char*)&st,sizeof(List));
cout<<st.course<<"\t"<<st.score<<endl; fboth.close(); return ;
}

(4)将文件指针定位从当前位置定位到下一门课程,读取该门课程的数据并显示出来;

C++:文件的输入和输出的更多相关文章

  1. 雷林鹏分享:C# 文件的输入与输出

    C# 文件的输入与输出 一个 文件 是一个存储在磁盘中带有指定名称和目录路径的数据集合.当打开文件进行读写时,它变成一个 流. 从根本上说,流是通过通信路径传递的字节序列.有两个主要的流:输入流 和 ...

  2. 雷林鹏分享:Ruby 文件的输入与输出

    Ruby 文件的输入与输出 Ruby 提供了一整套 I/O 相关的方法,在内核(Kernel)模块中实现.所有的 I/O 方法派生自 IO 类. 类 IO 提供了所有基础的方法,比如 read. wr ...

  3. 听翁恺老师mooc笔记(15)--文件的输入与输出

    <>重定向 如果使用标准的printf输出,有一个比较简便的方法,可以将程序的结果写入一个文件.使用<和>符号,将程序运行结果重定向到文件中去,具体使用到的代码如下: ./te ...

  4. C++_IO与文件4-简单文件的输入与输出

    通过键盘输入和屏幕输出被称为是控制台输入/输出: 更广义上讲控制台的输入/输出也是一种特殊的文件输入/输出: 当使用cin进行输入时,程序将输入视为一系列的字节,其中的每个字节都被解释成字符编码: 不 ...

  5. 【python】文件的输入和输出

    1.os模块 2.os.path 模块 3.实例 1. os模块 对文件系统的访问大多通过python的os模块实现,其中os 模块负责大部分的文件系统操作,包括删除/重命名文件,遍历目录树,管理文件 ...

  6. Linux命令总结_文件的输入与 输出

    1.echo命令 例子:echo string 解释:echo命令用于显示文本或变量,或者把字符串输入到文件,常用的几个特殊字符有以下几个 \c 不换行 \f 进纸 \t 调格 \n 换行 例子:ec ...

  7. Python 文件的输入与输出

    1. 文本文件的读写主要通过open()所构建的文件对象来实现.我们打开一个文件,并使用一个对象来表示该文件 , f = open(d,r) 其中d是文件名,r是模式 "r" 文件 ...

  8. 【Python+Selenium】猪猪练习成功版:csv文件的输入和输出(运行环境:python3.5版本)

    自己实践成功的从csv文件中读取用户名密码并实际登录系统后判断是否登录成功,并将已经运行的用户名密码及运行结果输出到一个新的csv文件中~ # coding=utf-8 from selenium i ...

  9. java之 ------ 文件的输入、输出(一)

    import java.io.*; public class IntFile { private String filename; public IntFile(String filename) { ...

随机推荐

  1. lua编程基础

    1.目前最新的lua版本是lua5.2.3 2.官网下载地址:http://www.lua.org/ftp/ 3.lua的初衷就是一个用于c/c++的小巧的脚本语言,本身是什么功能都没有的,需要手动用 ...

  2. Careercup - Google面试题 - 5661939564806144

    2014-05-06 01:40 题目链接 原题: Give a N*N matrix, print it out diagonally. Follow up, if it is a M*N matr ...

  3. [转]Similarities between Hibernate and JDBC objects

  4. 疑难杂症rendering(对角线上的线)

    postprocess全屏特效 对角线有条线 明显和buffer有关因为线由小的东西组成 就像之前没清空buffer产生的马赛克 beginscene时 clearmask 设0 ---------- ...

  5. Post 的数据被截断

    原因: Form 域 POST 提交数据 100K(可能不是这个值) 限制的解决方案   因为微软这个限制是对表单内每个域(第一个控件)的限制.问题的解决办法是,对于一个需要发送大数据的域,在提交表单 ...

  6. PowerDesigner(二)-项目和框架矩阵(转)

    项目和框架矩阵 项目是PowerDesigner 15的新概念,通过项目系统分析/设计人员可以对模型以及各类文档进行分组.项目也可以包含框架矩阵,以表格的形式体现各个模型之间的关系. 项目和框架矩阵解 ...

  7. 【JQuery NoviceToNinja系列】01 开篇 Html页面设计和布局

    01 开篇 Html页面设计和布局 index.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml ...

  8. js中的null VS undefined

    var a;------>undefined. JS变量的默认值.注意点在于判断变量的值为null.这是错误的.比如 if( a === null ) { // TODO; }; 实际上是und ...

  9. mongodb 主从服务器

    @set mongod=..\bin\mongod.exe set keyFile=key.key if not exist %keyFile% ( echo 123456>%keyFile% ...

  10. IOS Crash捕获

    IOS Crash ,就两种情况:一种是异常,另一种是中断[信号量]. #include <libkern/OSAtomic.h> #include <execinfo.h> ...