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

This commit is contained in:
8nlight 2023-10-04 17:12:38 +03:00
parent 424701f4fd
commit 74f22a1bd9
2 changed files with 133 additions and 0 deletions

18
src/chroot.c Normal file
View File

@ -0,0 +1,18 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(const int argc, const char **argv) {
if (argc <= 2) {
fprintf(stderr, "chroot: missing operand\n");
return 1;
}
chroot(argv[1]);
chdir("/");
for (int i = 2; i < argc; i++)
system(argv[i]);
}

115
src/wc.c Normal file
View File

@ -0,0 +1,115 @@
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
/* cmd arguments l - lines c - bytes w - words */
unsigned int l_flag;
unsigned int c_flag;
unsigned int w_flag;
unsigned int words;
unsigned int bytes;
unsigned int lines;
/* Total */
unsigned int twords;
unsigned int tbytes;
unsigned int tlines;
void count(const int fd) {
char buf[4096];
ssize_t n = 0;
int in_word = 1;
while ((n = read(fd, buf, sizeof(buf))) > 0) {
bytes += n;
for (ssize_t i = 0; i < n; i++) {
if (buf[i] == '\n')
lines++;
if (buf[i] == ' ' || buf[i] - '\t' < 5) {
if (!in_word) {
in_word = 1;
words++;
}
}
else
in_word = 0;
}
}
tbytes += bytes;
twords += words;
tlines += lines;
}
void print_count(const char *path, unsigned int plines, unsigned int pwords, unsigned int pbytes) {
if (l_flag)
printf("%u ", plines);
if (w_flag)
printf("%u ", pwords);
if (c_flag)
printf("%u", pbytes);
printf(" %s\n", path);
}
int main(const int argc, const char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-l"))
l_flag = 1;
else if (!strcmp(argv[i], "-c"))
c_flag = 1;
else if (!strcmp(argv[i], "-w"))
w_flag = 1;
else if (!strcmp(argv[i], "-h")) {
fprintf(stderr, "wc [-l (lines)] [-c (bytes)] [-w (words)] [file1 file2...]\n");
return 0;
}
}
if (!w_flag && !l_flag && !c_flag) {
w_flag = 1;
l_flag = 1;
c_flag = 1;
}
if (i == argc) {
count(STDIN_FILENO);
print_count("total", tlines, twords, tbytes);
}
for (; i < argc; i++) {
int fd = open(argv[i], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "wc: %s\n", strerror(errno));
return 1;
}
count(fd);
if (i == argc - 1)
print_count("total", tlines, twords, tbytes);
else
print_count(argv[i], lines, words, bytes);
close(fd);
words = bytes = lines = 0;
}
return 0;
}