C++文件读写操作



C++文件读写操作,相关的头文件:#include <fstream>

需要相关的类

fstream提供三种类,实现C++对文件的操作

ofstream:写操作,由ostream引申而来

ifstream:读操作,由istream引申而来

fstream :同时读写操作,由iostream引申而来

文件的类型:文本文件 和 二进制文件

文件读写的步骤:

1、包含的头文件:#include <fstream>

2、创建流

3、打开文件(文件和流关联)

4、读写 (写操作:<<,put( ), write( ) 读操作: >> , get( ),getline( ), read( ))

5、关闭文件:把缓冲区数据完整地写入文件, 添加文件结束标志, 切断流对象和外部文件的连接

文件的读写:

1、文本文件的读写:

方法:

一次性读写若干字符

1)使用运算符<< 和 >>进行读写

功能:

<< 能实现以行为单位写入文件

>> 不能一行为单位读入内存,总是以空格、Tab、回车结束,而是以单词为单位

代码:

函数功能:使用<< ,写入文件一行字符

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     ofstream OpenFile(“file.txt”);
  7.     if (OpenFile.fail())
  8.     {
  9.         cout<<”打开文件错误!”<<endl;
  10.         exit(0);
  11.     }
  12.     OpenFile<<”abc def ghi”;
  13.     OpenFile.close();
  14.     system(“pause”);
  15. }

运行结果:文件中写入内容:abc def ghi

函数功能:使用>>,从文件读入一个单词

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     const int len=20;
  7.     char str[len];
  8.     ifstream OpenFile(“file.txt”);
  9.     if (OpenFile.fail())
  10.     {
  11.         cout<<”打开文件错误!”<<endl;
  12.         exit(0);
  13.     }
  14.     OpenFile>>str;
  15.     cout<<str<<endl;
  16.     OpenFile.close();
  17.     system(“pause”);
  18. }

运行结果:str的内容为abc,而不是abc def ghi(见空格停止)

2)使用运算符<<(写)和getline()进行读写

功能:

<<:以行为单位输入文件

getline():以行为单位 读入内存,能一次读入一行

函数原型:istream &getline( char *buffer, streamsize num );

功能:getline( )函数用于从文件读取num-1个字符到buffer(内存)中,直到下列情况发生时,读取结束:

1):num – 1个字符已经读入

2):碰到一个换行标志

3):碰到一个EOF

代码:

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     const int len=20;
  7.     char str[len];
  8.     ifstream OpenFile(“file.txt”);
  9.     if (OpenFile.fail())
  10.     {
  11.         cout<<”打开文件错误!”<<endl;
  12.         exit(0);
  13.     }
  14.     OpenFile.getline(str,20);
  15.     cout<<str<<endl;
  16.     OpenFile.close();
  17.     system(“pause”);
  18. }

运行结果:str的内容为abc def ghi (一直把一行读完)

一次读写一个字符:

使用get( )和put( )函数

函数声明:istream& get(char &c);

函数功能:使用 get( )函数 把字符1输入到文件

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     char ch=’1′;
  7.     ofstream OpenFile(“file.txt”);
  8.     if (OpenFile.fail())
  9.     {
  10.         cout<<”打开文件错误!”<<endl;
  11.         exit(0);
  12.     }
  13.     OpenFile.put(ch);
  14.     OpenFile.close();
  15.     system(“pause”);
  16. }

运行结果:把字符1写入文件

函数功能:使用 put( )函数 把文件中第一个字符输入内存

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     char ch;
  7.     ifstream OpenFile(“file.txt”);
  8.     if (OpenFile.fail())
  9.     {
  10.         cout<<”打开文件错误!”<<endl;
  11.         exit(0);
  12.     }
  13.     OpenFile.get(ch);
  14.     cout<<ch;
  15.     OpenFile.close();
  16.     system(“pause”);
  17. }

运行结果:把字符1从文件中读到ch(内存)中

2、二进制文件的读写:

1)使用运算符get( ) 和 put( )读写一个字节

功能:

get( ) :在文件中读取一个字节到内存

函数原型:ifstream &get(char ch)

put( ) :在内存中写入一个字节到文件

函数原型:ofstream &put(char ch)

代码:

功能:把26个字符写入文件中

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     char ch=’a';
  7.     ofstream OpenFile(“file.txt”,ios::binary);
  8.     if (OpenFile.fail())
  9.     {
  10.         cout<<”打开文件错误!”<<endl;
  11.         exit(0);
  12.     }
  13.     for (int i=0;i<26;i++)
  14.     {
  15.         OpenFile.put(ch);
  16.         ch++;
  17.     }
  18.     OpenFile.close();
  19.     system(“pause”);
  20. }

运行结果:文件内容为abcdefghijklmnopqlst…z

功能:把文件中的26个字母读入内存

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     char ch;
  7.     ifstream OpenFile(“file.txt”,ios::binary);
  8.     if (OpenFile.fail())
  9.     {
  10.         cout<<”打开文件错误!”<<endl;
  11.         exit(0);
  12.     }
  13.     while (OpenFile.get(ch))
  14.         cout<<ch;
  15.     OpenFile.close();
  16.     system(“pause”);
  17. }

运行结果:ch依次为abc…z


2)使用read()和write()进行读写

read( ):

功能:从文件中提取 n 个字节数据,写入buf指向的地方中

函数声明:istream &  read ( char * buf ,  int  n ) ;

代码:

函数功能:使用write( )函数,一次从内存向文件写入一行数据

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     char ch[12]=”12 3 456 78″;
  7.     ofstream OpenFile(“file.txt”);
  8.     if (OpenFile.fail())
  9.     {
  10.         cout<<”打开文件错误!”<<endl;
  11.         exit(0);
  12.     }
  13.     OpenFile.write(ch,12);
  14.     OpenFile.close();
  15.     system(“pause”);
  16. }

运行结果:文件内容12 3 456 78

write( ):

功能:把buf指向的内容取n个字节写入文件

函数声明:ostream & ostream :: write ( char * buf ,  int  n ) ;

参数说明:buf表示要写入内存的地址,传参时要取地址。n表示要读入字节的长度

注意:1):该函数遇到空字符时并不停止,因而能够写入完整的类结构

2):第一个参数一个char型指针(指向内存数据的起始地址),与对象结合使用的时候,要在对象地址之前要char做强制类型转换。

函数功能:使用write( )函数,一次从文件向内存写入一行数据

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. void main()
  5. {
  6.     char ch[12];
  7.     ifstream OpenFile(“file.txt”);
  8.     if (OpenFile.fail())
  9.     {
  10.         cout<<”打开文件错误!”<<endl;
  11.         exit(0);
  12.     }
  13.     OpenFile.read(ch,12);
  14.     cout<<ch;
  15.     OpenFile.close();
  16.     system(“pause”);
  17. }

运行结果:数组ch的内容为12 3 456 78 。

说明:

1、程序不再使用文件时,为什么要关闭文件?

因为:1)文件缓冲区是一块小的内存空间.

            2)操作系统限制同时打开的文件数量 

注意:close ( ) 函数关闭文件,但流对象仍然存在。

2、文件的默认打开方式为文本文件,要是想以二进制的方式处理,在打开时要用 ios::binary 显式声明。

3、针对文本文件操作时,get函数和>>的区别:

区别:在读取数据时,get函数包括空白字符(遇空白字符不停止读取)
            >>在默认情况下拒绝接受空白字符(遇到空白符停止读取)
4、判断文件是否打开的方法:
  1. if (OpenFile)
  2. {
  3.     cout<<”打开文件失败!”;
  4.     exit(0);
  5. }
  6. if (OpenFile.fail())
  7. {
  8.     cout<<”打开文件错误!”<<endl;
  9.     exit(0);
  10. }
5、判断文件是否结束的方法:
         1)使用成员函数eof()可以检测到这个结束符,如果非0表示文件结束。
  1. while (!OpenFile.eof())
  2.     {
  3.         //文件结束时的代码
  4.     }
         2)使用流直接检测,如果为0表示文件结束
  1. while (!OpenFile)
  2.     {
  3.                   //文件结束时的代码
  4.     }
         3)使用get函数,读取最后一个结束符时,返回0.读取正常情况下,返回1,并把读取的字符放到ch中
  1. while ( (OpenFile.get(ch) )!=EOF)
  2.     {
  3.         //成功时候的代码
  4.     }

文本文件的读写常使用的方法:使用<<写入文件,使用getline 和 >> 读到内存

二进制文件的读写常使用的方法:使用istream 类的成员函数read 和write 来实现,

这两个成员函数的原型为:

  1. istream& read(char *buffer,int len);
  2. ostream& write(const char * buffer,int len);

参数说明:字符指针 buffer 指向内存中一段存储空间。len 是读/写的字节数。

与对象结合写入二进制文件时:

write函数调用语句:

  1. 输出文件流对象名.write((char*)& 对象名,sizeof(<对象所属类名>));
  2. 输出文件流对象名.write((char*)& 对象数组名[下标],sizeof(<对象所属类名>));

read函数调用语句:

  1. 输入文件流对象名.read((char*)& 对象名,sizeof(<对象所属类名>));
  2. 输入文件流对象名.read((char*)& 对象数组名[下标],sizeof(<对象所属类名>));

注意:gcount()函数经常和read函数配合使用,用来获得实际读取的字节数。

二进制文件的随机读写
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(void)
  5. {
  6.     //写文件:二进制存储1234
  7.     int writeNum1 = 1;
  8.     int writeNum2 = 2;
  9.     int writeNum3 = 3;
  10.     int writeNum4 = 4;
  11.     ofstream fout(“test.txt”, ios::out | ios::binary);
  12.     fout.write(reinterpret_cast<char *>(&writeNum1), sizeof(int));
  13.     fout.write(reinterpret_cast<char *>(&writeNum2), sizeof(int));
  14.     fout.write(reinterpret_cast<char *>(&writeNum3), sizeof(int));
  15.     fout.write(reinterpret_cast<char *>(&writeNum4), sizeof(int));
  16.     fout.close();
  17.     //读文件
  18.     ifstream fin(“test.txt”,ios::in | ios::binary);
  19.     if (!fin.good())
  20.     {
  21.         cout<<”文件打开错误”<<endl;
  22.         exit(0);
  23.     }
  24.     int readNum = 0;
  25.     //第一次输出:从第一个数字输出,结果是1 2 3 4
  26.     fin.seekg(0,ios::beg);
  27.     while (fin.peek() != EOF)
  28.     {
  29.         fin.read(reinterpret_cast<char*>(&readNum), sizeof(int));
  30.         cout<<readNum<<” ”;
  31.     }
  32.     cout<<endl;
  33.     //第二次输出:从第三个数字输出,结果是3 4
  34.     fin.seekg(2 * sizeof(int),ios::beg);//游标移动的次数 = 需要处理数的个数 × int占的字节数
  35.     while (fin.peek() != EOF)
  36.     {
  37.         fin.read(reinterpret_cast<char*>(&readNum), sizeof(int));
  38.         cout<<readNum<<” ”;
  39.     }
  40.     cout<<endl;
  41.     fin.close();
  42.     system(“pause”);
  43.     return 0;
  44. }