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

Posted

技术标签:

【中文标题】如何在 Visual Studio Express 2013(C++) 中获取特定驱动器的当前目录?【英文标题】:How to get current directory of a specific drive in Visual Studio Express 2013(C++)? 【发布时间】:2013-12-04 04:42:45 【问题描述】:

我正在将程序从 Borland C++ Builder 移植到 Visual Studio 2013 (C++)。该程序使用 getcurdir 来获取驱动器的当前目录。这个函数有一个参数驱动,但是微软的等效函数getcwd没有这个参数。我该怎么做?

【问题讨论】:

【参考方案1】:

当您标记 Visual Studio 时,我假设您使用的是 Windows。除了当前目录只是一个,(即可执行文件所在的位置或其他,如果你已经移动到),我认为当前目录不会因当前驱动器而有所不同。然后,在 Windows 中,您可以使用来自 winapi 的函数GetCurrentDirectory。原型是:

DWORD WINAPI GetCurrentDirectory(
  _In_   DWORD nBufferLength,
  _Out_  LPTSTR lpBuffer
);

您可以获取详细信息here。

示例:

TCHAR cwd[100];
GetCurrentDirectory(100,cwd);
// now cwd will contain absolute path to current directory

【讨论】:

【参考方案2】:

(是的,我知道这是一个旧条目,只是为了记录如果有人偶然发现同样的问题......)

正如deeiip 已经正确说过的那样,在 Windows 中只有 1 个当前目录,但是当 每个驱动器有 1 个当前目录时,cmd.exe 会伪造 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:\"!\r\nGiven value: \"driveLetter\".", nameof(driveLetter));
        return driveLetter;
    


【讨论】:

以上是关于如何在 Visual Studio Express 2013(C++) 中获取特定驱动器的当前目录?的主要内容,如果未能解决你的问题,请参考以下文章