【发布时间】: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 <arguments>的快捷方式,您会看到同样的问题。
标签: c++ windows command-line winrar