大家。我在尝试编写这个东西时遇到了困难,希望您能给我一些建议。 我正在尝试从文本文件中检索一些参数,然后将它们附加到 变量 char 数组,然后用管道执行该 char 数组,该命令是 bash 命令。
我的问题是如何访问文件以检索参数,我尝试过使用缓冲区和 string 但转换并没有真正帮助,这是我的代码的基本思想。
如果我将命令直接写入代码,则工作代码:
#include <string.h>
#include <cstdlib>
#include <cstdio>
char *out[10], line[256], command[] = {"mycommand parameter1 parameter2 ..."};
FILE *fpipe;
fpipe = (FILE*)popen(command,"r")
fgets(line, sizeof line, fpipe)
out[0] = strtok (line, "="); // <--- I'm tokenizing the output.
我从文件中读取的方法:
std::ifstream file("/path/to/file", std::ifstream::in);
//std::filebuf * buffer = file.rdbuf();
char * line = new char[];
//buffer->sgetn (line, lenght);
getline(file, line)
注释行是我尝试过的内容,还有其他内容,但我没有评论它们。
我正在考虑稍后将其移植到 C,但首先我想让它继续下去。 而且我还没有真正实现附加代码,因为我还无法读取该文件。 希望您能给我一些建议,谢谢!
最佳答案
你走在正确的轨道上,你只需要使用 std::string
这是 getline
接收的:
std::string line;
std::getline(file, line);
读取第一行行。但如果您需要将文件的全部内容读入 line
中,只需执行以下操作:
std::string line;
std::istreambuf_iterator<char> beg = file.rdbuf();
std::istreambuf_iterator<char> end;
line.assign(beg, end);
关于C++ 从文本文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821253/