[英]Issue with directories in c++.
我正在开发一个程序,但遇到了一些问题,这些问题正在发生。
基本上,该程序旨在为用户提供程序列表,一旦用户在程序上进行选择,便向用户提供所有带有相关扩展名的文件的列表。 选择文件后,它将使用所需程序打开文件。 现在我的问题是我的启动过程和扫描过程似乎在两个单独的目录中运行。 现在,我只是在桌面上有一个包含程序的文件夹。 当它运行时,它会随文件夹一起搜索,但是当打开文件时,它将尝试从同一文件夹的子文件夹dir中打开它们。 我相信问题出在搜索上,因为当我将.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 );
}
}
在此先感谢您可以为我提供的任何帮助。
如果该目录不是当前目录,则必须在文件名之前添加目录的路径,以便访问目录中的文件。
假设程序在C:/top-level
; 假设检查的目录是C:/another-one
。 当目录迭代器返回somefile.docx
,您需要使用C:/another-one/somefile.docx
来访问文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.