[英]How to filter out the result to get only file names in output result linux in c++98
[英]To Extract data from text file using c++98 linux
我正在嘗試從純文本文件中提取一些行。 其中包含 shell 腳本可執行文件的列表以及該特定 sh 文件的一些通用鍵。 需要從該文件中提取的所需數據應 exclude.sh 文件名和 MH_TEST 鍵。
例如:如果我的文件 abc.lst 包含
Cable_pull1.sh
MH_TEST PAR
DUAL_DOMAIN yes
CAMARO_STORAGE YES
Flagship.sh
MH_TEST NOR
10_Flags yes
Domain_Distibute.sh
MH_TEST NOR
fast_path YES
heavy_IO YES
如果傳遞的文件名為“ Cable_pull1.sh ”,則需要從上述文件abc.lst文件中提取的請求數據如下
DUAL_DOMAIN yes
CAMARO_STORAGE YES
如果文件名通過“ Flagship.sh ”,預計 output 如下,
10_Flags yes
下面是我試圖獲得結果的代碼,我有點迷失在提取所需信息的地方,請幫助我提取我正在尋找的信息
#include<iostream>
#include<string>
#include <fstream>
#include <cstring>
using namespace std;
bool findWord(string Filename, string const& find)
{
cout<<"Filename:"<<Filename<<"\t"<<"find:"<<find<<endl;
ifstream iFile(Filename.c_str());
if(!iFile)
{
cerr<<"File not opened!\n";
return false;
}
char c;
string content;
while(iFile.get(c) )
{
if(c != '\n')
{
content += c;
}
else
{
content = ""; //reset string after flag ',' was found
}
if(content == find)
return true;
}
cout<<"content:"<<content<<endl;
return false;
}
int main()
{
if(!findWord("abc.lst","Cable_pull1.sh"))
cout<<"failed"<<endl;
else
cout<<"success"<<endl;
return 0;
}
我會利用std::getline
將文件中的逐行讀入std::string
。 然后,您可以使用string
s 成員 function find
來查找您要查找的內容。
例如,當您找到Cable_pull1.sh
時,您循環,再次使用std::getline
並打印后面的行,直到找到空行。
例子:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
bool findWord(std::string Filename, std::string const& find) {
std::cout << "Filename:" << Filename << "\tfind:" << find << '\n';
std::ifstream iFile(Filename.c_str());
if(!iFile) {
std::cerr << "File not opened!\n";
return false;
}
std::string line;
while(std::getline(iFile, line)) { // read a whole line
// and find "find" in that line
std::size_t pos = line.find(find);
// if "find" is found (pos != std::string::npos),
// check that it's a full match to the rest of the line
if(pos != std::string::npos && line.substr(pos) == find) {
// ok, we found the correct entry in the file
// loop and print each line (except the "MH_TEST" lines)
while(std::getline(iFile, line)) {
if(line.size()==0) break; // empty line, break out
if(line.find("MH_TEST") == std::string::npos) {
// print lines not matching MH_TEST
std::cout << line << '\n';
}
}
return true;
}
}
return false;
}
int main() {
if(!findWord("abc.lst", "Cable_pull1.sh"))
std::cout << "failed\n";
else
std::cout << "success\n";
return 0;
}
Output:
Filename:abc.lst find:Cable_pull1.sh
DUAL_DOMAIN yes
CAMARO_STORAGE YES
success
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.