The something was most likely trying to read and write to the same file. The shell opens both for stdin and stdout at the same time, before launching the program, and opening for stdout truncates the file, so there’s nothing for stdin to read.
Edit:
Ok, then it wasn’t that. This topic is still quite relevant to “how would I delete a specific line in a file”, though.
Btw, hi @RuinedMango! Welcome to Ziggit.
This phenomenon is what makes deleting one line from a file tricky, in fact. If you do the obvious thing: open a file for reading, open the same file for writing, then stream the in file to the out file while skipping the lines you don’t want, it will just delete the file.
That’s because opening it for writing truncates the file, instantly. Which is basically never what you want.
One thing you can do is read the entire file into memory, and then open the same file for output, but we can do better than that. The problem with that approach is that there is a period where your original file only exists in memory: any syscall failure or other bug which brings the program down will destroy the file contents.
The maximally-paranoid way to do it is like this:
- open the file “a_file.txt” for reading
- open a temporary file “tmp/out_maybe_a_timestamp.txt” for writing
- stream the input file to the output file, flush, close the handle for the in file and the out file
- move the in file in the same directory, to “a_file.txt.old”
- move the temp file to the intended location “a_file.txt”
- then delete “a_file.txt.old”
The advantage of this approach is that the worst case outcome is that the new file is stranded in the tmp directory, and the old file is renamed a_file.txt.old
, which is a recoverable situation. A lot of old-school Unix tools do more-or-less exactly this.
It’s a lot of coding just to delete some lines! But it works.