如何在Visual Studio Express 2013(C++)中获取特定驱动器的当前目录

How to get current directory of a specific drive in Visual Studio Express 2013(C++)?

本文关键字:获取 驱动器 当前目录 C++ Visual Studio Express 2013      更新时间:2023-10-16

我正在将一个程序从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;
    }
}