PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 31, 2022

[FIXED] How to check last line of file for new_line character? C++

 October 31, 2022     c++, eof, file, getline, newline     No comments   

Issue

How can I check if the lastline in a file contains a '\n' (or newline).

Here are two examples: a file with newline at the end - a file without newline at the end

My current code:

fstream file("filename");
string line;
if (!file.is_open()) throw Exception();
while(getline(file, line))
{
    (checking for lastline)
}

I realized that getline won't contain the new_line character. I could go through each character, but there would be a performance problem. There are files with millions of characters and I don't know how to go to the end line to get the new_line character.

--- EDIT ---

  • Maybe I forgot to mention that my enviroment is UNIX only. So I will only use the end_line character '\n'.
  • Secondly, I need getline to check each line for some errors (but its not relevant here).
  • I will check my lastline before the while loop so I can sip it, if the file is invalid!
  • My images shows CR LF which is my bad. sry for the mistake. There should be only LF.

Solution

You can use seekg to jump to any position in the file.

file.seekg(-1,ios_base::end);    // go to one position before the EOF
char c;
file.get(c);                     // Read current character
if(c=='\n'){
    cout<<"yes"<<endl;           // You have new_line character
}

So we jump to one position before the EOF and read the last character. If it is a new line, you are done.



Answered By - Rishit Sanmukhani
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing