Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ remove trailing new line from text file

Is there a way in C++ to remove/trim a trailing new line from a text file?

For example

content content
content content
content content
<- this line in the text file is empty and needs to go ->
like image 442
NateTheGreatt Avatar asked Sep 18 '25 05:09

NateTheGreatt


2 Answers

Sure! One way to do it would be to read the file to a std::string

#include <fstream>
#include <string>

 // Add this code inside your main() function
std::ifstream ifs("filename.txt");      
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());

and then use any of the techniques described here:

C++ Remove new line from multiline string

then you could overwrite the file with the new result. Of course, this approach ain't practical when dealing with very large files (let's say, 2GB) but such thing is not a constraint according to your original question.

This thread also has great material on detecting new lines.

like image 151
karlphillip Avatar answered Sep 19 '25 20:09

karlphillip


ifstream fin("input.txt");
vector<string> vs;
string s;
while(getline(fin,s))
    vs.push_back(s);
fin.close();

ofstream fout("input.txt");
for(vector<string>::iterator it = vs.begin(); it != vs.end(); ++it)
{
    if(it != vs.begin())
        fout << '\n';
    fout << *it;
}
like image 36
Benjamin Lindley Avatar answered Sep 19 '25 18:09

Benjamin Lindley