在我的计划的下一步寻求帮助。
该程序现在所做的是,它询问用户他们正在寻找哪种类型的文件。一旦用户回答它,然后搜索该程序所在的文件夹,并找到扩展名与所请求类型匹配的所有文件。然后,它会列出所有匹配文件,并在其旁边显示一个与搜索迭代的数字。
我希望能够让用户只输入与他们想要打开的文件相对应的数字,然后将其打开。
我现在拥有的东西:
#include <iostream>
#include <filesystem>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
using namespace std::tr2::sys;
//Checks for matching extensions
bool ends_with(std::string& file, std::string& ext)
{
return file.size() >= ext.size() && // file must be at least as long as ext
// check strings are equal starting at the end
std::equal(ext.rbegin(), ext.rend(), file.rbegin());
}
//Checks for matching programs
bool program_match(std::string& file, std::string& reqFile)
{
return std::equal(reqFile.begin(), reqFile.end(), file.begin());
}
void wScan( path f, unsigned i = 0 )
{
directory_iterator d( f );
directory_iterator e;
vector<string>::iterator it2;
std::vector<string> extMatch;
std::vector<string> testMatch;
//loop that populates the vector of matches
for( ; d != e; ++d )
{
string file = d->path();
string ext = ".docx";
if(ends_with(file, ext))
{
extMatch.push_back(file);
}
}
int preI = -1;
for(it2 = extMatch.begin(); it2 != extMatch.end(); it2++)
{
preI += 1;
cout << preI << ". " << *it2 << endl;
}
cout << "Enter the number of your choice (or quit): ";
int fSelection;
cin >> fSelection;
//test match for full file match
for( ; d != e; ++d )
{
string file = d->path();
string reqFile = extMatch[fSelection];
if(program_match(file, reqFile))
{
testMatch.push_back(file);
}
}
for(it2 = extMatch.begin(); it2 != extMatch.end(); it2++)
{
cout << *it2 << endl;
}
}
int main()
{
string selection;
cout << "0. Microsoft word \n1. Microsoft Excel \n2. Visual Studio 11 \n3. 7Zip \n4. Notepad \n Enter the number of your choice (or quit): ";
cin >> selection;
path folder = "..";
if (selection == "0")
{
wScan ( folder );
}
else if...
}
我现在拥有的是另一个for循环,它再次遍历文件并拉出所有与所请求文件匹配的文件。然后打印出该文件的名称。没有理由这样做,这只是一个测试,看看我的搜索方法是否能找到我正在寻找的文件。
我想知道如何在找到文件后打开文件。我已经阅读了一些关于system()的东西,但它似乎被建议反对,但它对我来说无论如何都不适用于我。
谢谢!
答案 0 :(得分:0)
假设您的代码仅在Windows上运行(基于列出的程序),您可以使用ShellExecute
功能。要使用它,请包含Windows.h
并将要打开的程序和文件传递给函数:
#include <Windows.h>
int main()
{
char program[] = "VCExpress.exe";
char file[] = "main.cpp";
// opens file in program
ShellExecuteA(NULL, "open", program, file, NULL, SW_SHOWDEFAULT);
}
ShellExecute
还允许您在与文件扩展名关联的默认软件中打开文件。对我来说,以下内容也在Visual C ++中打开:
#include <Windows.h>
int main()
{
char file[] = "main.cpp";
// opens file in default program
ShellExecuteA(NULL, "open", file, NULL, NULL, SW_SHOWDEFAULT);
}
ShellExecute
可以执行包含更多选项的程序;查看文档:{{3}}