简体   繁体   中英

How to parse a part a file in C++ on Linux

I have a file called file.txt and it has this structure:

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

.
.
.

I want to get the value in fileSize. (1000 in this example.)

How do I get this information?

逐行读取文件,直到第二行,然后通过:读取strtok()第二行,您将有两个字符串: filesize1000 ,然后可以使用atoi()

Another easy way aside from strtok is to do a while (infile >> myString) . Just figure out the number of the value you want and take it out.

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
}

Split (partition) a line using 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;
        }
     }
  }
}

Output

1000

Related: Split a string in C++?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM