例如:我在 MS DOS 上,我在文件夹 C:\Documents and Settings\Programs 中有一个源代码。我可以让我的源代码使用随机文件夹中的程序(例如 gnuplot)吗?
5 回答
http://www.codeproject.com/KB/system/newbiespawn.aspx
ShellExecute 将查看 PATH 环境变量,因此您无需指定完整的 PATH。现在,如果它真的是一个随机位置并且它甚至不在 PATH 环境变量中,那么我猜你不走运。
如果它们甚至不在 PATH 中,那么您必须在候选文件夹中搜索它。这是有关如何在 C++中遍历文件系统路径的示例代码。
还有一个使用 Boost 的例子:
目录列表.h
#ifndef DIRECTORYLIST_H_INCLUDED
#define DIRECTORYLIST_H_INCLUDED
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <iostream>
#include <list>
#include <string>
class directoryList {
public:
directoryList();
~directoryList();
std::list<std::string> getListing(std::string path);
};
#endif // DIRECTORYLIST_H_INCLUDED
目录列表.cpp
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/convenience.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/progress.hpp"
#include "directoryList.h"
using namespace std;
namespace fs = boost::filesystem;
directoryList::directoryList() {}
directoryList::~directoryList() {}
list<string> directoryList::getListing(string base_dir) {
list<string> rv;
fs::path p(base_dir);
for (fs::recursive_directory_iterator it(p);
it != fs::recursive_directory_iterator(); ++it) {
string complete_filename = it->path().string();
rv.insert(rv.begin(),complete_filename);
}
return rv;
}
使用示例:
directoryList *dl = new directoryList();
filenames = dl->getListing("C:\\Program Files");
//search for the file here, or modify the getListing to supply a filter
还有一些核心函数_exec/exec及其修改。Linux 也有类似的功能。
源代码的位置与 system() 调用(我假设您使用该调用)定位程序的方式无关。唯一相关的考虑是编译的可执行文件的位置。
请查看 Windows 中的 PATH 环境变量 - 这就是找到程序的方式。这是一个以分号分隔的目录列表,Windows 在其中查找可执行文件和 BAT 文件和 DLL。在该列表中,当前目录和(我认为)您的 EXE 所在的位置都在前面。
PATH 是在 Windows XP 中通过系统控制面板小部件高级选项卡环境按钮设置的。对于 Vista,事情更复杂 - 您需要以管理员身份进行操作。
正如 Vinko 所说,PATH 环境变量决定了 Windows 将在何处查找程序文件。
通常最好避免将可执行文件的路径硬编码到已编译的程序中。即使 gnuplot 在您计算机上的特定文件夹中,它也可能不在其他人计算机上的同一文件夹中。这将导致您对其他程序的调用失败。您可以将其存储在注册表中并让用户配置程序位置,或提供搜索它的安装程序。
以下是一些选项:
- 在系统 PATH 中搜索要运行的可执行文件
- 允许用户在命令行上指定位置
- 将位置存储在配置文件中,并允许用户在安装期间(如果您有安装过程)或通过手动编辑文件来指定它
理想情况下你会做所有 3