C++ 从文本文件中读取

标签 c++ file-io command-line-arguments

大家。我在尝试编写这个东西时遇到了困难,希望您能给我一些建议。 我正在尝试从文本文件中检索一些参数,然后将它们附加到 变量 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/

相关文章:

batch-file - CMD 在参数中嵌套双引号

c++ - 找不到用户定义的 getline。自动扣款有问题?

java - 应用程序根目录中的相对路径 - Java Web 应用程序

c++ - 在 C++ 中打开文件 - getline 在第二次迭代时失败

c++ - 使用fstream时,文件的所有内容是否都加载到内存中?

c - 如何对 C 中的所有命令行参数求和?

java - 如何从命令行将数组 arg 传递给 Groovy JAR?

c++ - 堆栈最终会溢出吗?

c++ - _beginthread 在父构造函数中

c++ - 使用 STL 在 C++ 中对字符串进行标记