[英]C++ executing a code from a text file
标题说明了一切。 像编译器,但不一样。 我希望代码的某些部分可以从C ++的外部源中执行。 而且我不知道这是否可能实现,如Javascript,Python等。
假设我有一个名为sample.txt的文本文件,如下所示:
int a = 10, c;
cin >> c;
cout << a + c;
然后,我将在main()函数中调用文本文件并编译.exe文件。 当我运行它时,它是否有可能动态地表现为好像文件中的代码已嵌入其中并写入10+输入? 应该更改源文件,并且下次运行时将应用不同的结果。 顺便说一下,这只是示例代码,我可能想运行一些for / while循环以及if条件等。
PS:我知道如何读取文件并将其分配为整数或将其写入屏幕,这不是我想要的。 我需要通过编译功能。 谢谢。
有两种方法。
(虽然我意识到您是从C ++调用程序中请求的,但为了简单起见,我在bash中演示了这个想法。)
文件: run_it.sh
:
#!/bin/bash
set -e # Bail on the first error
FN_IN=./sample.txt
FN_WRAPPED=./wrapped.cc
FN_EXE=./wrapped
CC=g++
# Wrap the fragment in a full C++ program and compile it.
function build_wrapper () {
cat > $FN_WRAPPED <<'EOF'
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
EOF
cat $FN_IN >> $FN_WRAPPED
cat >> $FN_WRAPPED <<'EOF'
return 0;
}
EOF
$CC -o $FN_EXE $FN_WRAPPED
}
# Run the wrapper, passing input through STDIN and reading the output from STDOUT.
function run () {
local IN=$1
echo $IN | $FN_EXE
}
# Remove the wrapper (both code and compiled).
function clean_up () {
rm -f $FN_WRAPPED $FN_EXE
}
build_wrapper
IN=24
OUT=$(echo "$IN" | $FN_EXE)
echo "Result = $OUT"
echo "Another result = $(run 16)"
clean_up
$ ./run_it.sh
Result = 34
Another result = 26
这种方法非常强大,但是也有些牵扯。
简而言之,您想要
sample.txt
读取到内存中。 一些可能有用的链接:
编译后的C ++程序仅包含执行编译后的源代码所需的机器指令,语言标准未指定任何机制供用户在运行时生成其他机器指令。
为了提供脚本功能(响应输入文本的解析生成程序流的能力),您必须提供解析器和执行引擎。
int main()
{
std::string cmd;
int op1, op2;
while (cin >> cmd >> op1 >> op2) {
if (cmd == "add")
std::cout << op1 + op2 << "\n";
else if (cmd == "sub")
std::cout << op1 - op2 << "\n";
else
std::cerr << "error\n";
}
}
首先,许多解释语言都是用C或C ++编写的,因此通常可以将它们构建为库,然后将其合并到应用程序中,以便程序可以调用它们以提供嵌入式脚本语言。 这类语言的常见示例是Lua , Python和JavaScript 。 然后,您的程序可以将要执行的代码传递给解释器。
编写自己的lua解释器可能如下所示:
#include <iostream>
#include <string>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
bool get_input(std::string& in)
{
bool result;
do {
std::cout << "lua> " << std::flush;
result = std::getline(std::cin, in);
} while (result && in.empty());
return result;
}
int main (void) {
lua_State *L = lua_open(); // open lua
luaL_openlibs(L); // open standard libraries
std::string in;
while (get_input(in)) {
if (in.empty())
continue;
int error = luaL_loadbuffer(L, in.c_str(), in.size(), "line") ||
lua_pcall(L, 0, 0, 0);
if (error) {
std::cerr << lua_tostring(L, -1) << '\n';
lua_pop(L, 1); // remove the error message from the stack
}
}
lua_close(L);
}
在Linux下:
$ g++ -Wall -O3 -o mylua mylua.cpp -I/usr/include/lua5.1 -llua
$ ./mylua
lua> print("hello")
hello
lua> error
[string "line"]:1: '=' expected near '<eof>'
lua>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.