读取C++中的文件

Reading Files in C++

本文关键字:文件 C++ 读取      更新时间:2023-10-16

我正在寻找一种在我可以写入文件C++读取文件的方法,但这是我陷入困境的地方:

ifstream readfile;
readfile.open("C:/Users/Crazy/Desktop/Useless.txt")

我见过人们做这样的事情:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ifstream myReadFile;
    myReadFile.open("text.txt");
    char output[100];
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
            myReadFile >> output;
            cout << output;
        }
    }
    myReadFile.close();
    return 0;
}

但在

char output[100];

我想阅读整件事。

另外,我只想阅读它,而不是检查

它是否已经打开,而不是检查错误。我只想阅读整件事,而且只是整件事。

如果要

将整个文件读入变量,则需要:
1. 以字符为单位确定文件的大小。
2. 使用std::vector并声明该大小的向量,
或者使用 new 运算符并动态分配char数组。
3. 使用ifstream::read读取整个文件。
4. 关闭ifstream
5. 记得delete char缓冲区。

我建议使用操作系统 API 来确定文件长度。

编辑 1:示例

#include <iostream>
#include <fstream>
#include <vector>
std::ifstream my_file("my_data");
my_file.seekg(0, std::ios_base::end); // Seek to end of file.
const unsigned int file_length = my_file.tellg();
my_file.seekg(0);
std::vector<char> file_data(file_length);
my_file.read(&file_data[0], file_length);