Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unix 对stdin和stdout使用相同的文件并进行重定向_Unix_Pipe - Fatal编程技术网

Unix 对stdin和stdout使用相同的文件并进行重定向

Unix 对stdin和stdout使用相同的文件并进行重定向,unix,pipe,Unix,Pipe,我正在编写一个类似于过滤器的应用程序:它从一个文件(stdin)读取输入,处理并将输出写入另一个文件(stdout)。在应用程序开始写入输出文件之前,输入文件被完全读取 因为我使用的是标准输入和标准输出,所以我可以这样运行: $ ./myprog <file1.txt >file2.txt $ ./myprog <file.txt >file.txt $。/myprog file2.txt 它工作正常,但如果我尝试使用相同的文件作为输入和输出(即:从文件读取,然后写

我正在编写一个类似于过滤器的应用程序:它从一个文件(stdin)读取输入,处理并将输出写入另一个文件(stdout)。在应用程序开始写入输出文件之前,输入文件被完全读取

因为我使用的是标准输入和标准输出,所以我可以这样运行:

$ ./myprog <file1.txt >file2.txt
$ ./myprog <file.txt >file.txt
$。/myprog file2.txt
它工作正常,但如果我尝试使用相同的文件作为输入和输出(即:从文件读取,然后写入相同的文件),如下所示:

$ ./myprog <file1.txt >file2.txt
$ ./myprog <file.txt >file.txt
$。/myprog file.txt
在程序有机会读取它之前,它会清除
file.txt


在Unix中,有没有办法在命令行中执行类似的操作?

shell是用来处理输出文件的,因为它在执行程序之前准备输出文件句柄。在shell在单个shell命令行中重击文件之前,无法让程序读取输入

您需要使用两个命令,在读取文件之前移动或复制文件:

mv file.txt filecopy.txt
./myprog < filecopy.txt > file.txt

对于纯学术性质的解决方案:

$ ( unlink file.txt && ./myprog >file.txt ) <file.txt

$(unlink file.txt&./myprog>file.txt)包中有一个海绵工具:

/myprog
引用手册:

海绵读取标准输入并将其写入指定文件。与shell重定向不同,海绵在打开输出文件之前会吸收所有输入。这允许构造从同一文件读写的管道


请详细说明你的答案。奇怪。您的示例为什么不这样做,因为
$(./myprog>file.txt
截断file.txt的内容,顺便说一句,这是与
相同的文件,所以我们所要做的就是自己运行子shell。我想我知道答案,但我还是不知道为什么。。。
./myprog < file.txt | sponge file.txt