Using the same file for stdin and stdout with redirection

Viewed 4907

I'm writing a application that acts like a filter: it reads input from a file (stdin), processes, and write output to another file (stdout). The input file is completely read before the application starts to write the output file.

Since I'm using stdin and stdout, I can run is like this:

$ ./myprog <file1.txt >file2.txt

It works fine, but if I try to use the same file as input and output (that is: read from a file, and write to the same file), like this:

$ ./myprog <file.txt >file.txt

it cleans file.txt before the program has the chance to read it.

Is there any way I can do something like this in a command line in Unix?

3 Answers
Related