0
我正在研究一个程序,并且遇到了一些与directoy事情发生有关的问题。C++中的目录问题。
基本上,该程序旨在为用户提供一个程序列表,一旦用户选择了该程序然后向用户提供具有相关扩展名的所有文件的列表。选择一个文件后,它会随着所需的程序打开文件。我现在的问题是,我的启动程序和扫描程序似乎在两个独立的目录中运行。现在我只是在我的桌面上拥有包含该程序的文件夹。当它运行时,它会搜索文件夹,但是当打开文件时,它会尝试将它们从同一文件夹的子文件夹目录中打开。我相信问题出在搜索上,因为当我将.exe复制到另一个位置(例如桌面)时,它会从桌面打开文件夹,如果碰巧在我的文档中有一个匹配名称的文件。但是,如果桌面上没有匹配的文件,它将不会打开。
这里是我的代码怎么会有现在:提前
#include <iostream>
#include <filesystem>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
#include <Windows.h>
using namespace std;
using namespace std::tr2::sys;
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());
}
void wScan(path f, unsigned i = 0)
{
directory_iterator d(f);
directory_iterator e;
vector<string>::iterator it2;
std::vector<string> extMatch;
//iterate through all files
for(; d != e; ++d)
{
string file = d->path();
string ext = ".docx";
//populate vector with matching extensions
if(ends_with(file, ext))
{
extMatch.push_back(file);
}
}
//counter to appear next to file names
int preI = -1;
//display all matching file names and their counter
for(it2 = extMatch.begin(); it2 != extMatch.end(); it2++)
{
preI += 1;
cout << preI << ". " << *it2 << endl;
}
//ask for file selection and assign choice to fSelection
cout << "Enter the number of your choice (or quit): ";
int fSelection;
cin >> fSelection;
cout << extMatch[fSelection] << endl;
//assign the selected file to a string, launch it based on that string and record and output time
string s = extMatch[fSelection];
unsigned long long start = ::GetTickCount64();
system(s.c_str());
unsigned long long stop = ::GetTickCount64();
double elapsedTime = (stop-start)/1000.0;
cout << "Time: " << elapsedTime << " seconds\n";
}
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 (selection == "1")
{
eScan (folder);
}
else if (selection == "2")
{
vScan (folder);
}
else if (selection == "3")
{
zScan (folder);
}
else if (selection == "4")
{
tScan (folder);
}
}
感谢任何advide你可以给我。
这很有道理,我唯一的问题是,它不是在正确的目录中搜索,而是从正确的目录中打开文件。如果这是另一种方式,应该是一个简单的解决方案,但我不知道为什么它不是首先搜索正确的目录。 – Sh0
请注意,存储程序的目录不一定与当前目录运行时的目录相关。我不知道MSVS如何处理它,但它并不是不可信的,它将桌面作为当前目录而不是子目录。我建议查找'getcwd()'(获取当前工作目录)的MS等价物,并在程序中使用它来诊断发生了什么。你的'有时发现,有时找不到'的行为听起来像'程序没有运行你期望的当前目录'。 –