Pipe to my program as a log rotator

依然范特西╮ 提交于 2019-12-13 01:18:35

问题


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 LogRotator, then the command:

ls | ./LogRotator

Just concatenates all the file names together, like this:

LogRotatormain.oMakefile

while the output of ls is:

LogRotator main.o Makefile

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


回答1:


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;
}


来源:https://stackoverflow.com/questions/31894218/pipe-to-my-program-as-a-log-rotator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!