Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

C++ 如何查看是否有数据通过管道符传送到程序呢?

我想在 windows 下写一个类似 head 命令的程序,让它有以下两种用法:

  1. head 1.txt :输出 1.txt 前 10 行
  2. cat 1.txt | head :输出 1.txt 前10行

我发现第二种方式是通过 stdin 传递数据的,但是现在的问题是 我如何才能知道数据的来源是文件还是 stdin 呢?

使用参数名决定数据来源的话就会导致 cat 1.txt | head 这种方式不可用。
而如果使用子线程的话,子线程似乎并没有办法读取到主线程的 stdin。

而在主线程调用 cin 的话又会导致主线程被阻塞。而且 (bool)cin 也只有在读取到数据之后才有用。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
使用参数名决定数据来源的话就会导致 cat 1.txt | head 这种方式不可用。

head 就是用参数名决定来源的。

当没有文件名,或者文件名是 - 的时候,用 stdin


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...