truncate.c - ubase - suckless linux base utils
 (HTM) git clone git://git.suckless.org/ubase
 (DIR) Log
 (DIR) Files
 (DIR) Refs
 (DIR) README
 (DIR) LICENSE
       ---
       truncate.c (895B)
       ---
            1 /* See LICENSE file for copyright and license details. */
            2 #include <sys/stat.h>
            3 
            4 #include <fcntl.h>
            5 #include <stdio.h>
            6 #include <stdlib.h>
            7 #include <unistd.h>
            8 
            9 #include "util.h"
           10 
           11 static void
           12 usage(void)
           13 {
           14         eprintf("usage: %s [-c] -s size file...\n", argv0);
           15 }
           16 
           17 int
           18 main(int argc, char *argv[])
           19 {
           20         int cflag = 0, sflag = 0;
           21         int fd, i, ret = 0;
           22         long size = 0;
           23 
           24         ARGBEGIN {
           25         case 's':
           26                 sflag = 1;
           27                 size = estrtol(EARGF(usage()), 10);
           28                 break;
           29         case 'c':
           30                 cflag = 1;
           31                 break;
           32         default:
           33                 usage();
           34         } ARGEND;
           35 
           36         if (argc < 1 || sflag == 0)
           37                 usage();
           38 
           39         for (i = 0; i < argc; i++) {
           40                 fd = open(argv[i], O_WRONLY | (cflag ? 0 : O_CREAT), 0644);
           41                 if (fd < 0) {
           42                         weprintf("open: cannot open `%s' for writing:", argv[i]);
           43                         ret = 1;
           44                         continue;
           45                 }
           46                 if (ftruncate(fd, size) < 0) {
           47                         weprintf("ftruncate: cannot open `%s' for writing:", argv[i]);
           48                         ret = 1;
           49                 }
           50                 close(fd);
           51         }
           52         return ret;
           53 }