![](/img/trans.png)
[英]c++ get directory path, parse folder name, and print file content from parent directory
[英]Parse directory locations from file in c++
嗨,我有这样的txt文件:
Directory of C:\Users\RDep
01/09/2014 05:10 PM <DIR> .
01/09/2014 05:10 PM <DIR> ..
01/07/2014 09:32 PM 569 GNU CLISP 2.49.lnk
01/07/2014 09:38 PM 493 lsp 23.fas
01/07/2014 09:38 PM 28 lsp 23.lib
01/07/2014 09:35 PM 35 lsp 23.lsp
01/09/2014 05:02 PM <DIR> Sigma
01/09/2014 05:10 PM <DIR> Sxz
4 File(s) 1,125 bytes
Directory of C:\Users\RDep\Sigma
01/09/2014 05:02 PM <DIR> .
01/09/2014 05:02 PM <DIR> ..
0 File(s) 0 bytes
Directory of C:\Users\RDep\Sxz
01/09/2014 05:10 PM <DIR> .
01/09/2014 05:10 PM <DIR> ..
01/09/2014 05:10 PM 0 Zop.txt
1 File(s) 0 bytes
Total Files Listed:
5 File(s) 1,125 bytes
8 Dir(s) 46,734,090,240 bytes free
我只知道父目录是:C:\\ Users \\ RDep \\(取决于用户选择,并且在运行时可能会更改)。 并且结构类似于上面的代码。
这些其他名称和格式是未知的(zop.txt -lsp 23.lsp,...)
现在我要定位:
C:\Users\RDep
lsp 23.fas
lsp 23.lib
lsp 23.lsp
C:\Users\RDep\Sigma
Zop.txt
C:\Users\RDep\Sxz
我找不到任何有用的模式来查找这些字符串! 任何想法 ?
我认为“正则表达式”是个好方法,但是,在您的文件中,匹配模式非常简单。 因此,我只使用std::string
find
函数。 这段代码只是一个小片段。 因此,还有几个改进点。 例如,通过使用vector<string>
查找样式,将更容易添加查找样式和处理样式。
//Originally, each data is from your file.
//but, this is just sample.
std::istringstream input;
input.str("Directory of C:\\Users\\RDep\n"
"01/07/2014 09:32 PM 569 GNU CLISP 2.49.lnk\n"
"01/07/2014 09:38 PM 493 lsp 23.fas\n"
"01/07/2014 09:38 PM 28 lsp 23.lib\n"
"01/07/2014 09:35 PM 35 lsp 23.lsp\n");
//to find pattern
std::string directory_pattern = "Directory of ";
std::string lsp_pattern = "lsp ";
std::size_t found = std::string::npos;
for (std::string line; std::getline(input, line); ) {
found = line.find(directory_pattern);
if (found!=std::string::npos)
{
//write on file for 'directory'
std::string directory_name(line, found + directory_pattern.length() );
std::cout << "\nDirectory : " << directory_name;
continue;
}
found = line.find(lsp_pattern);
if (found!=std::string::npos)
{
//write on file for 'lsp'
std::string lsp_name(line, found );
std::cout << "\nlsp : " << lsp_name;
continue;
}
}
上面的代码将如下所示打印,
Directory : C:\\Users\\RDep
lsp : lsp 23.fas
lsp : lsp 23.lib
lsp : lsp 23.lsp
尝试类似:
bool foo(char* filename)
{
FILE* f = fopen(filename, "r");
if(f == NULL)
return false;
char buffer[1024];
char pattern[] = "C:\\Users\\RDep";
while(fgets(buffer, 1024, f) != NULL)
{
if(strstr(buffer, pattern) != null)
{
// Found pattern!
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.