C++读取文件的几种方式
在C++中,读取文件的几种方式有:
- 1、使用C++标准库中的ifstream类;
- 2、使用C++标准库中的fstream类;
- 3、使用C语言中的fopen函数;
- 4、使用Windows API函数;
- 5、使用第三方库。
下面我们将详细介绍以上几种方式:
1、使用C++标准库中的ifstream类
ifstream类是一个输入流类,它的作用是从文件中读取数据。使用ifstream类读取文件的步骤如下:
- 1)定义一个ifstream类的对象,并将其初始化为文件名;
- 2)使用ifstream类的open()函数打开文件;
- 3)使用ifstream类的getline()函数读取文件中的每一行;
- 4)使用ifstream类的close()函数关闭文件。
以下是使用ifstream类读取文件的示例代码:
#include#include using namespace std; int main() { ifstream inFile; inFile.open("data.txt"); if (!inFile) { cerr << "Unable to open file data.txt"; exit(1); // call system to stop } string line; while (getline(inFile, line)) { cout << line << endl; } inFile.close(); return 0; }
2、使用C++标准库中的fstream类
fstream类是一个输入/输出流类,它的作用是从文件中读取数据,也可以向文件中写入数据。使用fstream类读取文件的步骤如下:
- 1)定义一个fstream类的对象,并将其初始化为文件名;
- 2)使用fstream类的open()函数打开文件;
- 3)使用fstream类的read()函数读取文件中的内容;
- 4)使用fstream类的close()函数关闭文件。
以下是使用fstream类读取文件的示例代码:
#include#include using namespace std; int main() { fstream inFile; inFile.open("data.txt", ios::in); if (!inFile) { cerr << "Unable to open file data.txt"; exit(1); // call system to stop } char buf[256]; while (inFile.getline(buf, 256)) { cout << buf << endl; } inFile.close(); return 0; }
3、使用C语言中的fopen函数
fopen函数是C语言中的文件操作函数,它的作用是打开一个文件,以便读取或写入文件中的数据。使用fopen函数读取文件的步骤如下:
- 1)调用fopen函数,传入文件名和打开模式;
- 2)检查文件是否打开成功;
- 3)使用fgets函数读取文件中的每一行;
- 4)使用fclose函数关闭文件。
以下是使用fopen函数读取文件的示例代码:
#include#include int main() { FILE *fp; char buf[256]; fp = fopen("data.txt", "r"); if (fp == NULL) { fprintf(stderr, "Unable to open file data.txt"); exit(1); // call system to stop } while (fgets(buf, 256, fp) != NULL) { printf("%s", buf); } fclose(fp); return 0; }
4、使用Windows API函数
Windows API函数是Windows操作系统中提供的文件操作函数,它的作用是从文件中读取数据。使用Windows API函数读取文件的步骤如下:
- 1)调用CreateFile函数,传入文件名和打开模式;
- 2)检查文件是否打开成功;
- 3)使用ReadFile函数读取文件中的内容;
- 4)使用CloseHandle函数关闭文件。