c++ 文件读取函数总结

来源:互联网 发布:网络安全管理系统 编辑:程序博客网 时间:2024/05/17 23:09

c++ 文件读取函数总结

IO相关类继承关系
iostream.gif

本文讲解文件读写,因此主要介绍<fstream>相关类以及<stdio.h>fopen

ifstream

ifstream 是用来操作文件的输入流类。文件流通过构造函数或者通过调用open函数来完成与文件的绑定。

打开文件

  1. 通过构造函数
    std::ifstream ifs ("test.txt", std::ifstream::in);

  2. 通过open()函数

std::ifstream ifs;ifs.open("test.txt",std::ifstream::in);

一个一个字符读取 std::istream::get

可以一个一个读取并返回读取到的值,或者读取连续(n-1)个字符并保存在字符数组中。这种读取方式不怎么适用。

void getbychar(){    std::ifstream ifs("test.txt", std::ifstream::in);    char str[256];    ifs.get(str, 10); // 从ifs中读取10-1=9个字符,保存在str内    std::cout << "str: " << str << std::endl;    char c = ifs.get();  // 一次读取一个字符    while (ifs.good()) {        std::cout << c;        c = ifs.get();    }    ifs.close();}

一行一行读取

  • getline 函数 std::istream::getline
istream& getline (char* s, streamsize n );istream& getline (char* s, streamsize n, char delim );

一次读取一行,从流中读取字符并将其保存于c字符串中,知道遇到界定符delim(’\n’)或者已经向s写入了n个字符。

需要注意的是n要大于文件中最长的一行的字符数。如果此函数因为已经读取了n个字符而停止但是却没有找到界定符,那么failbit将会被设置。

void getbyline(){    std::ifstream ifs("test.txt", std::ifstream::in);    char str[256];    while(ifs.good()){ // 如果想测试只读取一行中一些字符,判断内可改为 !ifs.eof() && !ifs.fail()        ifs.getline(str,256);        std::cout << str << std::endl;    }   }
  • >> 操作符 std::istream::operator>>

>>操作符就和我们常用的cin>>一样的用法

void getlikecin(){    std::ifstream ifs("test.txt");    std::string str;    int num;    ifs >> num;    std::cout << num << std::endl;    while(ifs.good()){        ifs >> str;        std::cout << str << std::endl;    }       ifs.close();}

如果你运行了上面这个程序,你会发现,最后一个字符串会被输出两次!这是因为ifs完成最后一次读取后不会立即设置eof状态,所以程序会再进行一轮循环,在这轮循环ifs才会设置eof状态。结果就是最后一次读取的内容被输出了两次。

while循环可改为:

while(ifs>>str){std::cout << str << std::endl;}

或者

while(ifs.good()){    if(ifs >> str)        std::cout << str << std::endl;} 

stdio.h

C语言类型的文件读写,只需#include <stdio.h>即可。

打开文件
FILE * fopen ( const char * filename, const char * mode );
mode 可取

mode description “r” 读:打开一个文件进行读取操作。文件必须已经存在 “w” 写:创建一个空文件进行写操作。若同名文件已经存在,则会清空原文件的内容。 “a” 附加:打开一个文件,在文件末尾进行写操作。若文件不存在,则会创建新文件。 “+” 更新:需要和上述r/w/a进行结合,结合后文件将会变成即可读也可写。 “b” 二进制读写:需要和上述模式进行结合成”rb”,”wb”,”ab” “x” 避免重写已有文件:新C标准但不是C++的一部分,通过和”w”结合成”wx”,”wbx”等,若同名文件已存在,则会迫使此函数失败。
FILE *pFile;pFile = fopen("test.txt","r");

读取文件
int fscanf ( FILE * stream, const char * format, ... );
根据format声明的格式从stram中读取数据并保存在后面的参数中。这种读取适用于文件格式固定,每个字段类型确定的情况下进行读取操作。

#include <stdio.h>int main (){  char str [80];  float f;  FILE * pFile;  pFile = fopen ("myfile.txt","w+");  fprintf (pFile, "%f %s", 3.1416, "PI"); // 先向文件写入 3.1416 PI  rewind (pFile); // 设置pFile的位置指示回到文件开头  fscanf (pFile, "%f", &f);  // 读取一个浮点数  fscanf (pFile, "%s", str);  // 读取一个字符串  fclose (pFile);  printf ("I have read: %f and %s \n",f,str);  return 0;}
原创粉丝点击