【问题标题】:how to list a directory with _popen even though the path has a blank?即使路径为空白,如何使用 _popen 列出目录?
【发布时间】:2014-05-31 03:10:33
【问题描述】:

这是我在 Visual c++ 上的代码:

char dir[MAX_PATH]="";

sprintf(dir,"dir %s",cur_dir);//

FILE* cmd_dir=_popen(dir,"wt");

_pclose(cmd_dir);

如果我尝试将cur_dir 设置为"c:\""c:\perl64" 没有空格,它会起作用并且会列出目录中的文件。

但是,如果 cur_dirc:\program files,则它不起作用。即使我打开 command.exe(windows 终端)并输入dir c:\program files,它仍然不起作用。

请给我一些建议。

【问题讨论】:

  • sprintf(dir,"dir \"%s\"",cur_dir);?
  • 为什么要使用 _popen() 呢?有这方面的 API。
  • 我知道有很多方法可以解决这个问题。但是,以后对我会有帮助。

标签: c++ windows popen


【解决方案1】:

您需要将dir 的参数用引号括起来,否则底层shell 会将空格视为参数分隔符。

sprintf (dir, "dir \"%s\"", cur_dir);

目前"dir %s" 将扩展为dir c:\program files,这被视为您拥有dir "c:\program" "files"; IE。两个参数,而不是一个。

如果您打开 cmd 并编写以下内容,您应该会在您选择的目录中看到文件:

cmd "c:\program files"

注意:使用sprintf 时要小心,如果cur_dir 足够长,则可能会超出dir[MAX_PATH] 的范围。而是考虑使用更安全的snprintf,它要求您指定内容的最大长度:snprintf (dir, MAX_PATH, "dir \"%s\"", cur_dir);

注意:这个问题被标记为[c++],但是您的 sn-p 没有显示 C++ 的迹象 - 它看起来像 C。“C++ 的处理方式" 将包括使用std::string 来构建您的命令,并使用_popen (your_string.c_str (), "wt") 调用_popen

【讨论】:

  • @user1829967 欢迎来到 Stackoverflow,请将此答案标记为 已接受,以将线程标记为已解决。
【解决方案2】:

您需要在引号“”中捕获路径。

sprintf(dir,"dir \"%s\"",cur_dir);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 2020-09-11
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多