在C++中,要實(shí)現(xiàn)文件的隨機(jī)讀取,你可以使用<fstream>
庫中的seekg()
和tellg()
函數(shù)來定位文件指針。以下是一個(gè)簡單的示例:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>
int main() {
// 打開文件
std::ifstream file("example.txt", std::ios::binary | std::ios::in);
if (!file) {
std::cerr << "無法打開文件" << std::endl;
return 1;
}
// 獲取文件大小
file.seekg(0, std::ios::end);
std::streamsize fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// 創(chuàng)建緩沖區(qū)
std::vector<char> buffer(fileSize);
// 讀取文件內(nèi)容到緩沖區(qū)
if (!file.read(buffer.data(), fileSize)) {
std::cerr << "讀取文件失敗" << std::endl;
return 1;
}
// 關(guān)閉文件
file.close();
// 設(shè)置隨機(jī)數(shù)種子
std::srand(std::time(0));
// 隨機(jī)讀取文件
while (fileSize > 0) {
// 生成一個(gè)隨機(jī)位置
std::streamsize randomPos = std::rand() % fileSize;
// 將文件指針移動(dòng)到隨機(jī)位置
file.seekg(randomPos, std::ios::beg);
// 讀取一個(gè)字符
char randomChar;
file.get(randomChar);
// 輸出隨機(jī)字符
std::cout << randomChar;
// 更新文件大小和隨機(jī)位置
fileSize--;
}
return 0;
}
這個(gè)示例中,我們首先打開一個(gè)名為example.txt
的文件,并獲取其大小。然后,我們創(chuàng)建一個(gè)緩沖區(qū)并將文件內(nèi)容讀取到緩沖區(qū)中。接下來,我們?cè)O(shè)置隨機(jī)數(shù)種子,并在循環(huán)中隨機(jī)讀取文件內(nèi)容。每次迭代時(shí),我們都會(huì)生成一個(gè)隨機(jī)位置,將文件指針移動(dòng)到該位置,并讀取一個(gè)字符。最后,我們將讀取到的字符輸出到控制臺(tái)。