面试题答案
一键面试在C++中执行外部命令并处理错误,可以使用std::system
或popen
等函数。这里我们使用popen
函数,因为它允许我们读取命令的标准输出和标准错误,以便捕获错误信息。以下是代码结构设计的详细说明:
- 包含必要的头文件:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
- 定义执行命令的函数:
std::string executeCommand(const std::string& command) {
FILE* pipe = popen(command.c_str(), "r");
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
char buffer[128];
std::string result = "";
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != nullptr)
result += buffer;
}
int returnCode = pclose(pipe);
if (returnCode != 0) {
// 根据不同的返回码进行针对性处理
if (WIFEXITED(returnCode)) {
int status = WEXITSTATUS(returnCode);
if (status == 1) {
// 例如,返回码1可能表示输入文件不存在
std::cerr << "输入文件不存在" << std::endl;
} else if (status == 2) {
// 返回码2可能表示输出文件无法创建
std::cerr << "输出文件无法创建" << std::endl;
} else {
std::cerr << "命令执行失败,返回码: " << status << std::endl;
}
} else if (WIFSIGNALED(returnCode)) {
int signal = WTERMSIG(returnCode);
std::cerr << "命令被信号终止,信号: " << signal << std::endl;
}
throw std::runtime_error("命令执行失败");
}
return result;
}
- 主函数中调用执行命令的函数:
int main() {
try {
std::string command = "ffmpeg -i input.mp4 -c:v libx264 -preset medium -crf 23 output.mp4";
std::string output = executeCommand(command);
std::cout << "命令输出: " << output << std::endl;
} catch (const std::exception& e) {
std::cerr << "错误: " << e.what() << std::endl;
}
return 0;
}
代码说明
-
executeCommand
函数:- 使用
popen
打开一个管道来执行命令,并将命令的输出读取到result
字符串中。 - 使用
pclose
关闭管道,并获取命令的返回码。 - 根据返回码判断命令是否执行成功,如果失败,根据不同的返回码进行针对性处理,例如判断输入文件不存在、输出文件无法创建等常见错误情况。
- 如果命令执行失败,抛出
std::runtime_error
异常。
- 使用
-
main
函数:- 调用
executeCommand
函数执行转码命令。 - 使用
try - catch
块捕获可能抛出的异常,并输出错误信息。
- 调用
可扩展性
- 添加更多命令:可以在
main
函数中定义不同的命令字符串,并调用executeCommand
函数执行。 - 错误处理扩展:在
executeCommand
函数中,根据不同命令可能返回的错误码,继续添加更多的针对性错误处理逻辑,提高程序的健壮性。