簡體   English   中英

如何在Linux上的C ++中解析文件的一部分

[英]How to parse a part a file in C++ on Linux

我有一個名為file.txt的文件,它具有以下結構:

owner_name    : first_last_name
filesize      : 1000
is_legal_file : yes
date          : someDate

.
.
.

我想獲取fileSize中的值。 (在此示例中為1000。)

我如何獲得此信息?

逐行讀取文件,直到第二行,然后通過:讀取strtok()第二行,您將有兩個字符串: filesize1000 ,然后可以使用atoi()

除了strtok之外,另一種簡單的方法是執行while (infile >> myString) 只需弄清楚想要的值的數量並將其取出即可。

std::string myString;
ifstream infile("yourFile.txt");
while (infile >> myString)
{
    //Do an if-statement to only select the value you want.
    //Leaving this for you since I think it's homework
}

使用sstream分割(分割)線

#include <iostream>
#include <sstream>
#include <string>

int main() {
  using namespace std;
  for (string line; getline(cin, line); ) {
     istringstream ss(line);
     string name;
     ss >> name; // assume spaces between all elements in the line
     if (name == "filesize") {
        string sep;
        int filesize = -1;
        ss >> sep >> filesize;
        if (sep == ":" && ss) {
          cout << filesize << endl;
          break;
        }
     }
  }
}

輸出量

1000

相關: 在C ++中拆分字符串?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM