从文件中的特定位置查找文件中字符串的最后一次出现
Find last occurrence of a string in a file from a specific location in that file
我想从同一文件中的固定特定位置(分隔符)查找初始大小为 5MB
(最多可能达到 10MB
)的文本文件中字符串的最后一次出现。我找到了所有出现的情况,但是如何从特定位置打印最后一次/最后一次出现?
这是我的代码:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
string line;
char* str = "A-B";
file.open("test.txt");
unsigned int currline = 0;
while(getline(file, line)) {
currline++;
if (line.find(str, 0) != string::npos) {
cout << "found your search term: " << str << " at the " <<"line no.: " << currline << endl;
}
}
return 0;
}
以下是我的文本文件的示例数据:
A,A-B,127.0.0.1
B,B-C,127.0.0.1
# // *From this point I have to search downwards only!*
A-B_1,01-01-15,2,2,L
A-B_2,01-02-15,2,0,L
B-C_1,02-01-16,4,0,L
在每次迭代时将找到的文本分配给变量将覆盖变量内容,并且在循环结束后打印它将仅打印最后一次出现:
像这样的事情应该做:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
string line;
string found = "Nothing found";
char* str = "A-B";
file.open("test.txt");
unsigned int currline = 0;
while(getline(file, line)) {
currline++;
if (line.find(str, 0) != string::npos) {
found = line;
}
}
cout << found << endl;
return 0;
}
相关文章:
- foor 循环的最后一次迭代中的指针更改
- C++ 查找算法:如何找到元素的最后一次出现?
- 如何从文本文件中一次读取一个字符
- X 变量在最后一次尝试简单猜谜游戏时发生变化,C++
- 仅当捕获组最后一次出现时,才使字符成为可选字符
- C++ 向量元素被最后一次调用push_back替换
- 如何从文件中一次读取一个输入,类似于在c++中使用cin/scanf从控制台读取输入
- C 在子字符串内找到字符串的最后一次出现
- 如何在boost::d ynamic_bitset中找到一个的第一次和最后一次出现<>
- 使用 std::unique 和 vector.erase 删除除最后一次出现的重复元素之外的所有元素
- 删除字符C++最后一次出现时字符数组的开头
- std::getline 在最后一次出现分隔符后跳过来自 std::cin 的输入,但不跳过来自 std::istrin
- 逐行写入文件与一次写入全文
- 如何在最后一次EOL后删除文件的内容
- 如何在数组中查找特定值的第一次和最后一次出现
- 在线性搜索中查找int类型的最后一次出现
- 如何使用libgit2从git存储库中的HEAD获取最后一次提交
- 编译器是否可以自动生成std::move用于最后一次使用左值
- SQLite在最后一次引用共享行时删除该行
- 从文件中的特定位置查找文件中字符串的最后一次出现