gpt4 book ai didi

c++ - ifstream read 读取整个流的随机字符

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:27 25 4
gpt4 key购买 nike

我正在尝试实现 list 5.1 中的功能 here但是当从文件中读取并复制到缓冲区时,我只得到整个数组的相同字符 (Í),其中 string.txt 是从先前的链接内容复制和粘贴的。 enter image description here 这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cinttypes>
#include <cstdio>
#include <cstring>

const int block_size = 0x4000; //16KB

int search(char* buffer, int searchLength, char* stringToSearch, int stringToSearchLength) {
char * potentialMatch;
while (searchLength) {
potentialMatch = reinterpret_cast<char *>(memchr(buffer, *stringToSearch, searchLength));
if (potentialMatch == NULL)
break;

if (stringToSearchLength == 1) {
return 1;
} else {
if (!memcmp(potentialMatch + 1, stringToSearch + 1, stringToSearchLength - 1))
return 1;
}

searchLength -= potentialMatch - buffer + 1;
buffer = potentialMatch + 1;
}

return 0;
}


int main(int argc, char* argv[]) {
char *toSearch = "Interpreting Where";
int done = 0;
int found = 0;
char *buffer;
int64_t fileSizeLeft = 0;

std::ifstream myFile("string.txt");
if (!myFile.fail()) {
buffer = new char[block_size];
myFile.seekg(0, std::ios::end); //Get file's size
fileSizeLeft = myFile.tellg();
} else {
std::cout << "Cannot open file" << std::endl;
return 1;
}

int toSearchLength = strlen(toSearch);
int stringLeft = toSearchLength - 1;
int first_time = 1;


while (!done && fileSizeLeft > toSearchLength) {
if (first_time) {
myFile.read(buffer, block_size);
found = search(buffer, block_size, toSearch, toSearchLength);
} else {
memcpy(buffer, buffer + stringLeft, stringLeft);
myFile.read(buffer+stringLeft, fileSizeLeft-stringLeft);
found = search(buffer, block_size, toSearch, toSearchLength);
}

fileSizeLeft = fileSizeLeft - block_size;
first_time = 0;
}


if (found) {
std::cout << "String found" << std::endl;
} else {
std::cout << "String not found" << std::endl;
}

myFile.close();
delete[] buffer;

return 0;
}

希望你能帮我看看我做错了什么,谢谢!

最佳答案

您正在使用 seekgmyFile 的位置设置为 ios_base::end :

myFile.seekg(0, ios::end);

然后尝试从中读取:

myFile.read(buffer, block_size);

显然不会读取任何数据,因为 myFile 已经在 ios_base::end。您将读取 buffer

中已有的任何未初始化数据

你可能打算做的是在阅读之前通过这样做将你的 myFile 位置设置回开头:

myFile.seekg(0, ios::beg);

关于c++ - ifstream read 读取整个流的随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31687473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com