1 /* truncate.c - set file length, extending sparsely if necessary
3 * Copyright 2011 Rob Landley <rob@landley.net>
5 USE_TRUNCATE(NEWTOY(truncate, "<1s:|c", TOYFLAG_BIN))
11 usage: truncate [-c] -s SIZE file...
13 Set length of file(s), extending sparsely if necessary.
15 -c Don't create file if it doesn't exist.
16 -s New size (with optional prefix and suffix)
18 SIZE prefix: + add, - subtract, < shrink to, > expand to,
19 / multiple rounding down, % multiple rounding up
20 SIZE suffix: k=1024, m=1024^2, g=1024^3, t=1024^4, p=1024^5, e=1024^6
33 static void do_truncate(int fd, char *name)
39 if (TT.type == -1) size = TT.size;
42 if (TT.type<2) size += TT.size*(1-(2*TT.type));
44 if ((TT.type==2) ? (size <= TT.size) : (size >= TT.size)) return;
47 size = (size+(TT.type-4)*(TT.size-1))/TT.size;
51 if (ftruncate(fd, size)) perror_msg("'%s' to '%lld'", name, size);
54 void truncate_main(void)
56 int cr = !(toys.optflags&1);
58 if (-1 != (TT.type = stridx("+-<>/%", *TT.s))) TT.s++;
59 TT.size = atolx(TT.s);
61 // Create files with mask rwrwrw.
62 // Nonexistent files are only an error if we're supposed to create them.
63 loopfiles_rw(toys.optargs, O_WRONLY|O_CLOEXEC|(cr ? O_CREAT : 0), 0666, cr,