Загрузить файлы в «src»

This commit is contained in:
8nlight 2023-10-04 12:21:13 +03:00
parent 35b6fa68c7
commit 8949dade4a
2 changed files with 89 additions and 23 deletions

View File

@ -4,36 +4,50 @@
#include <string.h>
#include <unistd.h>
int cat(const int fd) {
unsigned int flag;
unsigned int lines;
void cat(const int fd) {
char buf[4024];
ssize_t len;
while ((len = read(fd, buf, sizeof(buf))) > 0)
if (write(STDOUT_FILENO, buf, len) != len)
return 1;
while ((len = read(fd, buf, sizeof(buf))) > 0) {
for (ssize_t i = 0; i < len; i++) {
if ((i > 0) ? buf[i - 1] == '\n' : 1 && flag)
printf(" %d ", ++lines);
return 0;
printf("%c", buf[i]);
}
}
}
int main(const int argc, const char **argv) {
if (argc == 1)
return cat(STDIN_FILENO);
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-n"))
flag = 1;
else if (!strcmp(argv[i], "-h")) {
printf("cat [-n] [file1 file2 ...]\n");
return 1;
}
}
if (i == argc)
cat(STDIN_FILENO);
else {
for (int i = 1; i < argc; i++) {
for (; i < argc; i++) {
int fd = open(argv[i], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "cat: %s %s\n", argv[i], strerror(errno));
return 1;
}
if (cat(fd))
return 1;
if (close(fd)) {
fprintf(stderr, "cat: %s %s\n", argv[i], strerror(errno));
return 1;
}
cat(fd);
close(fd);
}
}

View File

@ -1,7 +1,62 @@
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int get_stat(const char *path, struct stat *stat_path) {
if (stat(path, stat_path)) {
fprintf(stderr, "unable to stat %s: %s\n", path, strerror(errno));
return 1;
}
return 0;
}
int rmtree(const char *path) {
struct stat stat_path;
get_stat(path, &stat_path);
if (S_ISDIR(stat_path.st_mode) == 0) {
if (unlink(path) < 0) {
fprintf(stderr, "%s: is not directory\n", path);
return -1;
}
return 0;
}
DIR *dir = opendir(path);
if (dir == NULL) {
fprintf(stderr, "%s: Can`t open directory\n", path);
return -1;
}
struct dirent *ep;
while ((ep = readdir(dir)) != NULL) {
if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
continue;
char *full_path = malloc(strlen(path) + strlen(ep->d_name) + 1);
if (full_path == NULL) {
fprintf(stderr, "malloc() returned NULL\n");
return 1;
}
sprintf(full_path, "%s/%s", path, ep->d_name);
rmtree(full_path);
free(full_path);
}
closedir(dir);
if (rmdir(path) < 0)
fprintf(stderr, "%s: can`t remove a directory\n", path);
return 0;
}
int main(const int argc, char **argv) {
if (argc == 1) {
@ -9,12 +64,9 @@ int main(const int argc, char **argv) {
return 1;
}
for (int i = 1; i < argc; i++) {
if (unlink(argv[i]) < 0) {
fprintf(stderr, "rm: %s %s\n", argv[i], strerror(errno));
return 1;
}
}
for (int i = 1; i < argc; i++)
return rmtree(argv[i]);
return 0;
}