21xrx.com
2025-07-09 22:30:17 Wednesday
文章检索 我的文章 写文章
C++读取文件函数
2023-06-29 03:46:55 深夜i     20     0
C++语言 文件读取 函数 I/O操作 文件流处理

C++是一种面向对象的编程语言,具有高效的运行速度和易于学习的特点。在实际应用中,C++经常需要读取文件来获取数据或操作文件,因此掌握C++读取文件函数是非常必要的。

C++文件读取函数主要有以下几种:

1. fstream函数

fstream函数是C++标准库中最基本的文件读取函数,它包含在 头文件中。通过fstream函数,我们可以直接打开文件、读取文件内容以及关闭文件。

示例代码:

#include <fstream>
#include <iostream>
using namespace std;
int main () {
 char buffer[256];
 ifstream myfile ("example.txt"); // 打开文件
 if (myfile.is_open()) { // 判断文件是否打开成功
  while (! myfile.eof() ) { // 判断文件是否到达末尾
   myfile.getline (buffer,256); // 读取一行文件内容
   cout << buffer << endl; // 输出文件内容
  }
  myfile.close(); // 关闭文件
 }
 else cout << "Unable to open file"; // 文件打开失败
 return 0;
}

2. fread函数

fread函数则是利用C语言中的函数来进行文件的读取和写入。fread函数主要包含于 头文件中。通过该函数,我们可以一次性读取指定个数的数据。

示例代码:

#include<cstdio>
using namespace std;
int main () {
  int length = 1024;
  char buffer[length];
  FILE * pFile;
  pFile = fopen ("example.txt", "rb"); // 打开文件,并且二进制读数据
  if (pFile==NULL) perror ("Error opening file"); // 文件打开失败
  else {
   fread(buffer,1,length,pFile); // 读取文件内容到缓冲区
   fclose (pFile); // 关闭文件
  }
  return 0;
}

3. getline函数

getline函数又被称为“获取一行数据”的函数,它位于 头文件中,并且主要用于读取文本文件中的一行内容。

示例代码:

#include<iostream>
#include<fstream>
using namespace std;
int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open()) { // 判断文件是否打开成功
   while ( getline (myfile,line) ) { // 逐行读取文件内容
    cout << line << '\n'; // 输出文件内容
   }
   myfile.close(); // 关闭文件
  }
  else cout << "Unable to open file"; // 文件打开失败
  return 0;
}

在实际编程中,我们可以根据实际需要选择不同的读取函数进行文件操作处理。

  
  

评论区