一、打开文件
使用ifstream类可以方便地读取文件内容。在使用ifstream类时,首先需要打开文件。打开文件的代码示例如下:
#include <fstream>
using namespace std;
int main() {
  ifstream fin;
  fin.open("example.txt");
  if (!fin.is_open()) {
    cout << "文件打开失败!" << endl;
    return 1;
  }
  // 其他操作
  fin.close();  // 关闭文件
  return 0;
}
在示例中,首先声明一个ifstream对象fin,然后通过其open()函数打开文件example.txt。在打开文件后,可以通过is_open()函数来判断文件是否打开成功。如果成功,is_open()函数将返回true,否则返回false。
二、读取文件内容
在打开文件成功后,就可以使用ifstream对象的相关函数来读取文件内容。常用的函数有get()、getline()、read()、peek()和ignore()。
1、使用get()函数读取文件内容
get()函数用于从文件中读取一个字符。调用get()函数时,当前文件指针将向前移动一个字符。代码示例如下:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ifstream fin;
  fin.open("example.txt");
  if (!fin.is_open()) {
    cout << "文件打开失败!" << endl;
    return 1;
  }
  char c;
  while (fin.get(c)) {
    cout << c;
  }
  fin.close();  // 关闭文件
  return 0;
}
在示例中,使用while循环和get()函数逐个读取文件中的字符,并输出到控制台。
2、使用getline()函数读取文件内容
getline()函数用于从文件中读取一行内容。调用getline()函数时,当前文件指针将移到下一行的起始位置。代码示例如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
  ifstream fin;
  fin.open("example.txt");
  if (!fin.is_open()) {
    cout << "文件打开失败!" << endl;
    return 1;
  }
  string line;
  while (getline(fin, line)) {
    cout << line << endl;
  }
  fin.close();  // 关闭文件
  return 0;
}
在示例中,使用while循环和getline()函数逐行读取文件内容,并输出到控制台。
3、使用read()函数读取文件内容
read()函数用于从文件中读取指定数量的字节。代码示例如下:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ifstream fin;
  fin.open("example.txt", ios::binary);
  if (!fin.is_open()) {
    cout << "文件打开失败!" << endl;
    return 1;
  }
  const int BUF_SIZE = 1024;
  char buf[BUF_SIZE];
  while (fin.read(buf, BUF_SIZE)) {
    cout.write(buf, fin.gcount());
  }
  fin.close();  // 关闭文件
  return 0;
}
在示例中,使用while循环和read()函数逐块读取文件内容,并输出到控制台。需要注意的是,read()函数需要指定打开文件的方式为二进制模式(ios::binary),否则在读取二进制文件时可能会导致数据丢失或错乱。
三、关闭文件
在使用完文件后,需要调用ifstream对象的close()函数来关闭文件:
fin.close();
四、完整代码示例
下面是一个完整的使用ifstream类读取文件内容的示例代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
  ifstream fin;
  fin.open("example.txt");
  if (!fin.is_open()) {
    cout << "文件打开失败!" << endl;
    return 1;
  }
  // 逐个字符读取文件内容
  char c;
  while (fin.get(c)) {
    cout << c;
  }
  // 逐行读取文件内容
  string line;
  fin.clear();  // 清除文件流状态,将文件指针移到文件开头
  fin.seekg(0, ios::beg);
  while (getline(fin, line)) {
    cout << line << endl;
  }
  // 逐块读取文件内容
  const int BUF_SIZE = 1024;
  char buf[BUF_SIZE];
  fin.clear();  // 清除文件流状态,将文件指针移到文件开头
  fin.seekg(0, ios::beg);
  while (fin.read(buf, BUF_SIZE)) {
    cout.write(buf, fin.gcount());
  }
  fin.close();  // 关闭文件
  return 0;
}
在示例中,首先使用get()函数逐个字符读取文件内容,然后使用getline()函数逐行读取文件内容,最后使用read()函数逐块读取文件内容。
原创文章,作者:DMOMG,如若转载,请注明出处:https://www.506064.com/n/313764.html
 
 微信扫一扫
微信扫一扫  支付宝扫一扫
支付宝扫一扫 