我正在编写一个 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
非常感谢所有帮助!
最佳答案
首先,程序 latex
和 dvipdf
的路径需要在您的 PATH
环境变量中。
其次,通过 system
调用 shell 是完全独立的(实际上每次都会启动一个新的 shell 实例)。因此,如果您在一个目录中切换目录,这不会影响其他目录。通过以下方式切换程序的当前目录:
chdir(directory.c_str())
你需要这个
#include <cunistd>
using namespace std;
在文件的开头。
请注意,如果不仔细检查参数(在您的情况下是文件名),则可以很容易地利用依赖于输入参数的命令行调用system
来运行任意命令。由于您没有引号,如果有例如,程序将失败。文件名中的空格。
关于C++ 程序无法通过 system() 函数调用找到 latex 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18401502/