2

大家。我在尝试编写代码时遇到了困难,希望您能给我一些建议。我正在尝试从文本文件中检索一些参数,然后将它们附加到变量 char 数组中,然后用管道执行该 char 数组,该命令是 bash 命令。

我的问题是如何访问文件以检索参数,我尝试过使用缓冲区和字符串,但转换并没有真正帮助,这是我的代码的基本思想。

如果我将命令直接写入代码,则工作代码:

#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,但首先我想让它继续运行。而且我还没有真正实现附加代码,因为我还不能读取文件。希望您能给我一些建议,谢谢!

4

3 回答 3

2

您走在正确的轨道上,您只需要使用接收的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);
于 2013-11-06T19:43:25.113 回答
1

std::getline()需要istream和作为string参数。

istream& getline (istream& is, string& str);

这是文档:http ://www.cplusplus.com/reference/string/string/getline/

于 2013-11-06T19:58:56.377 回答
0

我建议做类似的事情:

#include <string>
#include <fstream>

std::istream file("/path/to/file"); //ifstream is only infile

std::string astringpar;
float afloatingpar;
//in this example there is a string and a float in the file
//separated by space, tab or newline
//you can continue/replace with int or other in fonction of the content

while (file >> astringpar >> afloatpar)
{
//here do what you want with the pars
}

ciao冰

于 2013-11-06T19:48:43.647 回答