micro-utils/coreutils/truncate.c

56 lines
960 B
C
Raw Normal View History

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