Is there a way to open()
a file and cause it to shrink? One can, of course, open them in append-mode or seek to the end and write to cause them to grow. However, as far as I know, there is no method to shrink a file via typical unix-style system call interfaces.
The only way to do so, as far as I know, is by faking it by creating a new shorter file and rename()
it in place of the older one.
I just wanted confirmation, because I saw an answer that implied that it was possible to make file editors that worked directly on a file instead of going through the process of making a new one and renaming it in place.
I've always thought that the file api in libc and unix-style system call interfaces did not allow for the shrinking of files to ease implementation of filesystems and maybe avoid usage patterns that might contribute to fragmentation.
fopen
in mode "w" (or "w+") will truncate it to zero length automatically. Or do you mean shrinking to a non-zero size, to preserve some of the old contents?open()
andopenat()
already have a flag for truncating,O_TRUNC
so technically it does cause the file to shrink - that is, shrink completely - without changing inode. Most famous example of that iscommand > file.txt
, where file will be truncated if it exists. If you runstrace
onbash -c 'true > /dev/null'
you'll seeopenat(AT_FDCWD, "/dev/null", O_WRONLY|O_CREAT|O_TRUNC, 0666)
in the output. Of course for variable size of truncation you needtruncate()
syscall. Let me know if you want this as an actual answer instead of the comment.