ban*_*run 9 c++ macos clang llvm-clang clang++
我试图用C++编写代码,就像tail -f在linux中一样.我发现了这个问题:
如何在C++中阅读不断增长的文本文件?并实现了相同的.我创建了一个temp.txt并开始做echo "temp" >> temp.txt.但是我的程序没有打印对文件所做的更新.我做错了什么?这是我正在使用的代码
#include <iostream>
#include <string>
#include <fstream>
#include <unistd.h>
int main()
{
std::ifstream ifs("temp.txt");
if (ifs.is_open())
{
std::string line;
while (true)
{
while (std::getline(ifs, line)) std::cout << line << "\n";
if (!ifs.eof()) break; // Ensure end of read was EOF.
ifs.clear();
sleep(3);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
我在linux机器上尝试了相同的代码并且它工作正常,但它不适用于Mac.我gcc用来编译代码.
gcc -v 给
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
Run Code Online (Sandbox Code Playgroud)
更新2
我进一步调查并意识到我毕竟不使用gcc.我已经单独安装了gcc,现在工作正常.这是一个错误clang吗?
小智 2
缓冲区很可能cout在您的测试中未刷新,因为缓冲区大小未达到溢出限制。std::cout << line << std::endl;您可以尝试通过执行代替std::cout << line << "\n";或调用std::cout.flush()lbefore来刷新缓冲区sleep(1);。这两种方法都应该与 clang 和 gcc 一起可靠地工作。
这些问题的答案很好地解释了缓冲:
| 归档时间: |
|
| 查看次数: |
338 次 |
| 最近记录: |