Home > OS >  Reading numbers from a chosen line in a file C
Reading numbers from a chosen line in a file C

Time:01-26

I want to know if I can read numbers from a chosen line in a file in c .For example if I have .txt file like :

2 3
1 2 3 4
4 5 6 7

There are 3 lines, how can I read only the numbers on line 2 without having to read anything else?

CodePudding user response:

Unless you know the exact file offset of the second line from a previous call to std::istream::tellg, then you will have to read the first line in order to get to the position of the second line. You can use the function std::getline for reading the first line as a std::string, or you can use std::istream::ignore to read and discard the first line, like this:

input.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); 

If you do happen to know the exact offset of the second line, then you can call std::istream::seekg in order to directly jump to that offset.

Note, howevever, that a file offset does not necessarily correspond to the number of characters that you see when reading the file in text mode. For example, on different platforms, line endings may consist of a different number of characters, which get translated to the single character \n when reading the file in text mode. However, the file offset required by std::istream::seekg is the offset in binary mode. Therefore, you should generally not attempt to calculate such an offset yourself (unless you opened the stream in binary mode, which you should not do for text files). You should only use the function std::istream::tellg for obtaining such an offset.

CodePudding user response:

You can read the file line by line in C using

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
    fstream newfile;
    newfile.open("file.txt",ios::in);
    if (newfile.is_open()){ 
        string tp;
        int i=0;
        while(getline(newfile, tp)){ 
            if (i==1) {
                cout << tp << endl; // this will only print the second line
            }
            i =1;
         }
         newfile.close();
    }
}
  •  Tags:  
  • Related