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等價物,並在程序中使用它來診斷髮生了什麼。你的'有時發現,有時找不到'的行爲聽起來像'程序沒有運行你期望的當前目錄'。 –