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 ->
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With