【问题标题】:C++ Read from text fileC++ 从文本文件中读取
【发布时间】:2013-11-07 06:39:30
【问题描述】:

大家。我在尝试编写代码时遇到了困难,希望您能给我一些建议。 我正在尝试从文本文件中检索一些参数,然后将它们附加到 变量 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,但首先我想让它继续运行。 而且我还没有真正实现附加代码,因为我还不能读取文件。 希望您能给我一些建议,谢谢!

【问题讨论】:

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


    【解决方案1】:

    您在正确的轨道上,您只需要使用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);
    

    【讨论】:

    • 谢谢,帮了大忙
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      我会建议做类似的事情:

      #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 冰

      【讨论】:

        猜你喜欢
        • 2020-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-21
        • 2021-12-19
        相关资源
        最近更新 更多