0

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?

Mat
  • 202,337
  • 40
  • 393
  • 406
user1106106
  • 277
  • 2
  • 7
  • 13

3 Answers3

1

Read the file line by line until the second line, then strtok() the second line by : and you'll have two strings: filesize and 1000, then you could use atoi().

Paul
  • 20,883
  • 7
  • 57
  • 74
  • is it possible just to read the second line? ( because it's actially the 15th line.. and i want to save time instead of reading the file line by line) – user1106106 Dec 26 '11 at 15:26
  • I don't think that's possible. – Paul Dec 26 '11 at 15:30
  • It's not possible. You have to read the file to find the line separators. If it was at a known offset, you could seek to the position, but that doesn't seem like your case. Anyway, worrying about going through 15 lines in a file definitely qualifies as premature optimization. – dlowe Dec 26 '11 at 15:35
0

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
}
John Humphreys
  • 37,047
  • 37
  • 155
  • 255
0

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++?

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • thanks. is there a way to do this by using char* instead of string? – user1106106 Dec 26 '11 at 16:15
  • @user1106106: if you use `char*` then [`strtok_r()`](http://www.kernel.org/doc/man-pages/online/pages/man3/strtok_r.3.html) is more appropriate. – jfs Dec 26 '11 at 16:27