如何在Visual Studio Express 2013(C++)中获取特定驱动器的当前目录
How to get current directory of a specific drive in Visual Studio Express 2013(C++)?
我正在将一个程序从Borland C++Builder移植到Visual Studio 2013(C++)。该程序使用getcurdir获取驱动器的当前目录。这个函数有一个参数驱动,但微软的等效函数getcwd没有这样的参数。我该怎么做?
当您标记visualstudio时,我假设您使用的是windows。除此之外,当前目录只是一个(即可执行文件所在的位置或其他位置,如果您已移动到),我认为当前目录不会因当前驱动器而异。然后,在windows中,您可以使用winapi中的函数GetCurrentDirectory
。原型是:
DWORD WINAPI GetCurrentDirectory(
_In_ DWORD nBufferLength,
_Out_ LPTSTR lpBuffer
);
您可以在此处获取详细信息
示例:
TCHAR cwd[100];
GetCurrentDirectory(100,cwd);
// now cwd will contain absolute path to current directory
(是的,我知道这是一个旧条目,只是为了在有人遇到相同问题时记录…)
正如deeiip已经正确地说的,在Windows中只有一个当前目录,但cmd.exe在每个驱动器有1个当前目录时伪造DOS行为。
如果您需要访问cmd的每个驱动器的当前目录,请使用相应的隐藏环境变量,例如"%=C:%"。
这里有一个示例应用程序(在C#中):
using System;
static class Module1 {
public static void Main(String[] args) {
var myFolder = GetCurrentFolderPerDrive(args[0]); //e.g. "C:"
Console.WriteLine(myFolder);
}
private static string GetCurrentFolderPerDrive(string driveLetter) {
driveLetter = NormalizeDriveLetter(driveLetter);
string myEnvironmentVariable = $"%={driveLetter}%";
string myResult = Environment.ExpandEnvironmentVariables(myEnvironmentVariable);
if (myResult == myEnvironmentVariable) return $"{driveLetter.ToUpperInvariant()}\"; //No current folder set, return root
return myResult;
}
private static String NormalizeDriveLetter(String driveLetter) {
if (String.IsNullOrWhiteSpace(driveLetter)) throw new ArgumentNullException(nameof(driveLetter), "The drive letter is null, empty or white-space.");
Boolean throwException = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".IndexOf(driveLetter[0]) < 0);
if (!throwException) {
if (driveLetter.Length == 1) {
driveLetter += ':';
} else if (driveLetter.Length != 2) {
throwException = true;
}
}
if (throwException) throw new ArgumentException($"A well-formed drive letter expected, e.g. "C:"!rnGiven value: "{driveLetter}".", nameof(driveLetter));
return driveLetter;
}
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何使用libusb获取驱动器名称?
- 如何获取我的驱动器中具有特定扩展名的所有文件的列表
- 如何从驱动器字母中获取驱动器名称
- 使用Qstorageinfo获取网络驱动器的名称
- 获取闪存驱动器的读写速度
- 如何获取物理驱动器的卷 ID?
- 获取<whatever>包含正在运行的可执行文件的 USB 驱动器C++ /dev/
- 在本地机器上获取可用的物理驱动器
- 正在从驱动器号获取NTFS卷GUID
- 如何在C++中使用WMI获取硬盘的所有逻辑驱动器的可用空间
- 如何在Visual Studio Express 2013(C++)中获取特定驱动器的当前目录
- 如何获取有关设备驱动器的信息
- 在DOS 7.x中获取大型驱动器结构信息
- 使用libudev获取Linux中挂载驱动器的信息
- Windows XP:如何从磁盘驱动器号获取USB设备位置
- 如何在Qt应用程序中获取MAC OS中驱动器的文件格式
- 如何在C/ c++中获取磁盘驱动器序列号?