管道到我的程序作为日志旋转器 [英] Pipe to my program as a log rotator

查看:136
本文介绍了管道到我的程序作为日志旋转器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现自己的日志旋转器(创建新的日志文件,每当文件大小达到10 MB)。读取标准输入并将其写入文件的部分是:

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

但问题是管道数据被破坏。标签和新行总是丢失。例如,如果我的程序的名称是 LogRotator ,则命令:

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 ls 的输出是:

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.?

推荐答案

感谢DieterLücking的提示,我找到了办法。所以一个必须使用未格式化的读。以下工作正常:

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

这篇关于管道到我的程序作为日志旋转器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆