C++ 程序无法通过 system() 函数调用找到 latex 命令

标签 c++ macos compilation latex

我正在编写一个 C++ 程序,它必须自动生成一些数据供学生在综合练习中使用。我已经将这些数据导出到 .tex 文件,并且还希望 C++ 程序能够自动编译这些 tex 文件。

通常我会通过执行以下操作从命令行编译 tex 文件:

$ latex file.tex
$ latex file.tex
$ dvipdf file.dvi

所以我尝试在我的 C++ 代码中执行以下操作(目录和文件名都是字符串):

//Move to the location where I created the files
string mycommand = "cd ";
mycommand += directory;
system(mycommand.c_str());
//Compile latex
mycommand = "latex " + filename + "_main.tex";
system(mycommand.c_str());
system(mycommand.c_str());
//Create .pdf
mycommand = "dvipdf " + filename + "_main.dvi";
system(mycommand.c_str());

然后在终端输出中产生以下错误消息:

sh: latex: command not found
sh: latex: command not found
sh: dvipdf: command not found

我在网上搜索过这个问题,但我没能找到解决这个问题的方法,尽管我相信这可能是非常简单的事情。

我在 OSX 上工作并安装了以下版本的 latex :

pdfTeX 3.1415926-2.4-1.40.13 (TeX Live 2012)
kpathsea version 6.1.0

非常感谢所有帮助!

最佳答案

首先,程序 latexdvipdf 的路径需要在您的 PATH 环境变量中。

其次,通过 system 调用 shell 是完全独立的(实际上每次都会启动一个新的 shell 实例)。因此,如果您在一个目录中切换目录,这不会影响其他目录。通过以下方式切换程序的当前目录:

chdir(directory.c_str())

你需要这个

#include <cunistd>
using namespace std;

在文件的开头。

请注意,如果不仔细检查参数(在您的情况下是文件名),则可以很容易地利用依赖于输入参数的命令行调用system来运行任意命令。由于您没有引号,如果有例如,程序将失败。文件名中的空格。

关于C++ 程序无法通过 system() 函数调用找到 latex 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18401502/

相关文章:

c++ - 如何编码要用于模板参数的类型列表?

c++ - 读取 64 位整数文件

c++ - CPP int 到语句问题中的字符串

macos - SMJobBless 仅适用于 kSMDomainSystemLaunchd,需要 kSMDomainUserLaunchd

c++ - 我可以让 clang 生成函数指针的绝对地址吗?

java - 发布(编译)java程序而不发布源代码

compilation - 为什么D编译需要这么长时间?

c++ - __userpurge 调用 (IDA)

android - configchanges编译错误

macos - 在MacOS上为 Electron 应用程序构建dmg需要2-3分钟