micro-utils/coreutils/truncate.c
2023-11-07 16:56:14 +03:00

56 lines
960 B
C

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
unsigned int c_flag = 0;
unsigned int s_size = 0;
int opt;
while ((opt = getopt(argc, argv, "s:c")) != -1) {
switch (opt) {
case 's':
s_size = atoi(optarg);
break;
case 'c':
c_flag = 1;
break;
default:
printf("truncate [file]\n\t[-c Do not create files] [-s=SIZE]\n");
return 0;
}
}
argv += optind;
argc -= optind;
if (argc == 0) {
fprintf(stderr, "truncate: missing operand\n");
return 1;
}
int flags = O_WRONLY | O_NONBLOCK;
if (!c_flag)
flags |= O_CREAT;
int fd = open(argv[0], flags, 0666);
if (fd < 0) {
fprintf(stderr, "truncate %s %s\n", argv[0], strerror(errno));
return 1;
}
if (ftruncate(fd, s_size) == -1) {
close(fd);
fprintf(stderr, "truncate %s %s\n", argv[0], strerror(errno));
return 1;
}
close(fd);
return 0;
}