Search code examples
c++fileoperation

Read part of txt file with C++


I have a question regarding reading a *.txt file with C++. I'm trying to read only the part of data between some specific sign like [start] and [end].

How I can do that?

I know how to open and read the whole file but I don't know how to read only a part of it with such requirements.


Solution

  • Use std::string and std::getline to filter out lines and go from there. Example:

    std::ifstream input("someText.txt");
    std::string line;
    unsigned int counter = 0;
    while (std::getline(input, line))
    {
        std::cout << "line " << counter << " reads: " << line << std::endl;
        counter++;
    }
    

    Furthermore you can use the substr() method of the std::string class to filter out sub strings. You can also tokenize words (instead of lines) with std::getline using the optional third argument, which is the tokenizer. Example:

    std::ifstream input("someText.txt");
    std::string word;
    unsigned int counter = 0;
    while (std::getline(input, word, ' '))
    {
        std::cout << "word #" << counter << " is: " << word << std::endl;
        counter++;
    }