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

This commit is contained in:
8nlight 2023-10-03 23:09:17 +03:00
parent ccbc9bcef3
commit acd5298cb4
5 changed files with 163 additions and 0 deletions

41
src/cat.c Normal file
View File

@ -0,0 +1,41 @@
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
int 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;
return 0;
}
int main(const int argc, const char **argv) {
if (argc == 1)
return cat(STDIN_FILENO);
else {
for (int i = 1; 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;
}
}
}
return 0;
}

14
src/echo.c Normal file
View File

@ -0,0 +1,14 @@
#include <stdio.h>
int main(const int argc, const char **argv) {
if (argc > 1) {
for (int i = 1; i < argc; i++) {
fputs(argv[i], stdout);
if (i < argc - 1)
putchar(' ');
}
}
putchar('\n');
return 0;
}

15
src/getloadavg.c Normal file
View File

@ -0,0 +1,15 @@
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double avg[3] = {0, 0, 0};
#ifndef __ANDROID__
if (getloadavg(avg, sizeof(avg) / sizeof(avg[0])) < 0) {
fprintf(stderr, "getloadavg: getloadavg() failed\n");
return 1;
}
#endif
printf("%.2f %.2f %.2f\n", avg[0], avg[1], avg[2]);
}

74
src/ls.c Normal file
View File

@ -0,0 +1,74 @@
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
int list(const char *path, int flag, int label) {
struct stat statbuf;
if (stat(path, &statbuf)) {
fprintf(stderr, "unable to stat %s: %s\n", path, strerror(errno));
return 1;
}
/* If its file */
if (!S_ISDIR(statbuf.st_mode)) {
puts(path);
return 0;
}
/* Make label */
if (label)
printf("\n%s: \n", path);
/* Open and print dir */
struct dirent *ep;
DIR *dp = opendir(path);
if (dp == NULL) {
fprintf(stderr, "%s: %s\n", path, strerror(errno));
return 1;
}
while ((ep = readdir(dp)) != NULL) {
if (ep->d_name[0] == '.' && !flag)
continue;
puts(ep->d_name);
}
closedir(dp);
return 0;
}
int main(const int argc, const char **argv) {
int flag = 0;
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-a"))
flag = 1;
else if (!strcmp(argv[i], "-h")) {
printf("ls [-a] [Path]\n");
return 0;
}
}
if (i == argc)
return list(".", flag, 0);
if (i == argc - 1)
return list(argv[i], flag, 0);
else
for (int i = 1; i < argc; i++)
if (list(argv[i], flag, 1))
return 1;
return 0;
}

19
src/pwd.c Normal file
View File

@ -0,0 +1,19 @@
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
int main(void) {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)))
puts(cwd);
else {
fprintf(stderr, "pwd: %s\n", strerror(errno));
return 1;
}
return 0;
}