【问题标题】:Extracting .rar/.zip using c++使用 C++ 提取 .rar/.zip
【发布时间】:2015-05-23 13:20:42
【问题描述】:

没有什么特别的原因,我目前正在开发一个使用 system() 提取 .zip/.rar 文件的程序。

我目前安装了 WinRar,因为 winrar.exe 能够处理 .zip 和 .rar 文件。

int main()
{
    vector<wstring> files;

    if (ListFiles(L"folder", L"*", files))
    {
        string program = "\"C:\\Program Files\\WinRAR\\winrar.exe\"";
        string args = "x -y";
        string type = "*.*";

        TCHAR dir[MAX_PATH];
        GetCurrentDirectory(MAX_PATH, dir);
        wstring current_directory(wstring(L"\"") + dir + wstring(L"\\"));

        for (const auto& f : files)
        {
            if (wcscmp(PathFindExtension(f.c_str()), L".rar") == 0 ||
                wcscmp(PathFindExtension(f.c_str()), L".zip") == 0)
            {
                string file = ws2s(f.c_str());
                string output = "\"c:\\Users\\my name\\Desktop\\output\"";

                string command = program + " " + args + " " + ws2s(current_directory) + file + "\"" + " " + type + " " + output;
                cout << command << endl;

                if (system(command.c_str()) != 0)
                    return GetLastError();
            }
        }
    }

    return 0;
}

因为我使用的是命令行,并且不希望空格成为问题,所以我将我可以用引号括起来:
-- "C:/users/username/program files (x86)/" --
-- "folder/zipped folder.zip" vs folder/"zipped folder.zip" --

在构建了包含在command 中的完整命令后,我将其打印到屏幕上以便我可以编辑->标记:
"C:\Program Files\WinRAR\winrar.exe" x -y "C:\Users\my name\Documents\Visual Studio 2013\Projects\extractor\folder\unzip.zip" *.* "c:\Users\my name\Desktop\output"

但是,'C:\Program' is not recognized as an internal or external command, operable program or batch file. 是我在system(command) 通话后遇到的。

如果我将完全相同的命令复制并粘贴到“开始”->“命令提示符”中,它就像做梦一样。

How to extract ZIP files with WinRAR command line?
http://comptb.cects.com/using-the-winrar-command-line-tools-in-windows/
https://www.feralhosting.com/faq/view?question=36

有没有其他方法可以调用system() 调用?
如果没有,还能如何使用命令行参数?

我宁愿 [完全避免] 不使用 Boost:: 或 3rd 方库。

谢谢!

【问题讨论】:

  • 可能和这个somewhat quirky behavior of Command Prompt有关(间接影响system)。解决方案是在传递给system整个字符串周围添加一组额外引号。
  • @Rufflewind 实际上做到了。有趣...我以前在使用命令提示符时从未遇到过这个问题。
  • 不直接在命令提示符中。您需要在外部调用 CMD 以使问题变得明显(例如,创建一个链接到 cmd.exe /c &lt;arguments&gt; 的快捷方式,您会看到同样的问题。

标签: c++ windows command-line winrar


【解决方案1】:

这可能是因为quirky behavior of Command Prompt 在引用参数时。每当你调用system("\"arg1\" \"arg2\""),就相当于调用:

cmd.exe /c "arg1" "arg2"

由于链接帖子中描述的奇怪行为,命令提示符将无法正确解释。需要额外的一组引号:

cmd.exe /c ""arg1" "arg2""

对于调用可执行文件,CreateProcess 提供了一种替代方法,让您可以更好地控制进程。您仍然需要引用参数,但 rules are a bit simpler 作为命令提示符不再妨碍您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2012-07-23
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 2016-08-25
    • 2015-06-27
    相关资源
    最近更新 更多