如何在C++中以文件流的形式读取文本文件?

2024-11-02 10:16:28
推荐回答(1个)
回答1:

// read a file into memory
#include // std::cout
#include 败升 // std::ifstream

int main () {

std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
// get length of file:
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);

char * buffer = new char [length];

std::cout << "Reading " << length <大袜< " characters... ";
// read data as a block:
is.read (buffer,length);

if (is)
std::cout << "all characters read successfully.";
else
std::cout << "error: only " << is.gcount() <滚枯激< " could be read";
is.close();

// ...buffer contains the entire file...

delete[] buffer;
}
return 0;
}