The Quantum Physicist The Quantum Physicist - 1 month ago 5x
Linux Question

Pipe to my program as a log rotator

I'm trying to implement my own log rotator (create new log file whenever filesize reaches 10 MB). The part that reads the standard input and writes it to the file is this:

fstream file("log.txt", ios::out | ios::app);
while (std::cin >> lineInput) {
file << lineInput;

But the problem is that piped data gets ruined. Tabs and new lines are always lost. So for example if my program's name is
, then the command:

ls | ./LogRotator

Just concatenates all the file names together, like this:


while the output of

LogRotator main.o Makefile

My question: How can I make the standard streaming preserve everything, including tabs, newlines, etc.?


Thanks to Dieter L├╝cking's hint, I found the way to do it. So one has to use an unformatted read. The following works fine:

fstream file("log.txt", ios::out | ios::app);
while (getline(cin,lineInput,'\n'))
    file << lineInput;