Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i read first line from file?

Tags:

c++

ifstream infile;

string read_file_name("test.txt");

infile.open(read_file_name);

string sLine;

    while (!infile.eof())
    {
        getline(infile, sLine);         
        cout << sLine.data() << endl;
    }

    infile.close();

This program prints all line in the file, but I want to print only first line.

like image 892
user2036891 Avatar asked Feb 14 '13 04:02

user2036891


People also ask

How do I read the first line of a text file?

Open a file using open(filename, mode) as a file with mode “r” and call readline() function on that file object to get the first line of the file.

How do I read a file line by line?

The readLine() method of BufferedReader class reads file line by line, and each line appended to StringBuffer, followed by a linefeed. The content of the StringBuffer are then output to the console.

How do I read the first line of a file in Shell?

Just echo the first list of your source file into your target file. For which head -n 1 source. txt > target.


1 Answers

while (!infile.eof()) does not work as you expected, eof see one useful link

Minor fix to your code, should work:

  ifstream infile("test.txt");

  if (infile.good())
  {
    string sLine;
    getline(infile, sLine);
    cout << sLine << endl;
  }
like image 144
billz Avatar answered Sep 22 '22 05:09

billz