【问题标题】:read in txt file in C++在 C++ 中读取 txt 文件
【发布时间】:2013-04-30 09:11:12
【问题描述】:

我有一个这样的 .txt 参数文件:

#Stage
filename = "a.txt";
...

#Stage
filename = "b.txt";
...

基本上我想在每次访问参数文件时读取一个阶段。 我打算在 C++ 中使用带有分隔符“#Stage”的 getline 来执行此操作。或者有更好的方法来解决这个问题?任何示例代码都会有所帮助。

【问题讨论】:

  • “或者有更好的方法来解决这个问题?” - 以什么方式更好?如果#Stage 是文件结尾的标记[或您要阅读的内容的结尾],那么这就是您必须做的。
  • 任何代码示例:istream& getline (istream& is, string& str, char delim);,编辑:更好的方法,始终是一个可靠的序列化程序 - 它让我很开心每个人都是如何开始阅读 .txt 或 .csv 的,而不是从 dom 开始/xml 之类的

标签: c++ ifstream getline


【解决方案1】:
*struct content{
    DATA data;
    content* next;
};
struct List{
    content * head;
};

static List * list;
char buf[100];
FILE * f = fopen(filename);
while(NULL != fgets(buf,f))
{
    char str[100] ={0};
    sccanf(buf,"%s",str);
    if(strcmp("#Stage",str) == 0)
    {
        // read content and add to list
        cnntent * p = new content();
        list->add();

    }
    else
    {
        //update content in last node
        list->last().data = 
    }
}*

【讨论】:

    【解决方案2】:

    也许我应该表达得更清楚。无论如何,我是这样管理的:

    ifstream file1;
    file1.open(parfile, ios::binary);
    if (!file1) {
        cout<<"Error opening file"<<parfile<<"for read"<<endl;
        exit(1);
    }
    
    std::istreambuf_iterator<char> eos;
    std::string s(std::istreambuf_iterator<char>(file1), eos);
    
    unsigned int block_begin = 0;
    unsigned int block_end = string::npos;
    
    for (unsigned int i=0; i<stage; i++) {
    
        if(s.find("#STAGE", block_begin)!=string::npos) {
        block_begin = s.find("#STAGE", block_begin);
        }
    }
    
    if(s.find("#STAGE", block_begin)!=string::npos) {
    block_end = s.find("#STAGE", block_begin);
    }
    
    
    string block = s.substr(block_begin, block_end);
    
    stringstream ss(block);
    ....
    

    【讨论】:

      【解决方案3】:

      我会逐行阅读,忽略以# 开头的行(或内容为#Stage 的行,具体取决于格式/目标)(因为没有getline 版本,采用@987654324 @ 作为分隔符)。

      【讨论】:

      • 我不知道发生了什么...我可以将char作为分隔符吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多