micro-utils/coreutils/truncate.c
2023-11-06 18:32:22 +03:00

53 lines
999 B
C

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(const int argc, const char **argv) {
unsigned int c_flag = 0;
unsigned int s_size = 0;
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strncmp(argv[i], "-s=", 3))
s_size = atoi(argv[i] + 3);
else if (!strcmp(argv[i], "-c"))
c_flag = 1;
else if (!strcmp(argv[i], "--help")) {
printf("truncate [-c Do not create files] [-s=SIZE] file1 file2...\n");
return 0;
}
}
if (argc - i == 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[i], flags, 0666);
if (fd < 0) {
fprintf(stderr, "truncate %s %s\n", argv[i], strerror(errno));
return 1;
}
if (ftruncate(fd, s_size) == -1) {
close(fd);
fprintf(stderr, "truncate %s %s\n", argv[i], strerror(errno));
return 1;
}
close(fd);
return 0;
}