Files

117 lines
2.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/reboot.h>
#include <sys/ioctl.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdbool.h>
// #include "para.h"
#include "builtin.h"
void cmd_cd(char *path) {
if (!path) path = "/";
if (chdir(path) != 0) perror("cd");
}
void cmd_pwd() {
char buf[1024];
if(getcwd(buf, sizeof(buf))) printf("%s\n", buf);
}
void cmd_ls(char *path) {
DIR *d = opendir(path ? path : ".");
struct dirent *dir;
if (d) {
while ((dir = readdir(d)) != NULL) if(dir->d_name[0] != '.') printf("%s ", dir->d_name);
printf("\n"); closedir(d);
} else perror("ls");
}
// void cmd_cat(int argc, const char *argv[]) {
// if (argc < 2) {
// printf("Usage: cat <file1> [file2] ...\n");
// return;
// }
// char buf[1024];
// int n, fd;
// for (int i = 1; i < argc; i++) {
// fd = open(argv[i], O_RDONLY);
// if (fd < 0) {
// perror(argv[i]);
// continue;
// }
// while ((n = read(fd, buf, sizeof(buf))) > 0) {
// write(STDOUT_FILENO, buf, n);
// }
// close(fd);
// }
// }
// void cmd_proc() {
// const int argc = 2;
// const char* args[] = {"cat", "/proc/cpuinfo", NULL};
// cmd_cat(argc, args);
// }
// void cmd_echo(int argc, const char *argv[]) {
// int start_index = 1;
// int no_newline = 0;
// if (argc > 1 && strcmp(argv[1], "-n") == 0) {
// no_newline = 1;
// start_index = 2;
// }
// for (int i = start_index; i < argc; i++) {
// printf("%s", argv[i]);
// if (i < argc - 1) {
// printf(" ");
// }
// }
// if (!no_newline) {
// printf("\n");
// }
// fflush(stdout);
// }
void cmd_poweroff() { sync(); reboot(RB_POWER_OFF); }
void cmd_reboot() { sync(); reboot(RB_AUTOBOOT); }
void cmd_size() {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0) {
printf("Terminal Size: %d rows x %d cols\n", ws.ws_row, ws.ws_col);
} else {
perror("size: failed to get window size");
}
}
void cmd_resize(char* row, char* col) {
struct winsize ws;
ws.ws_row = atoi(row);
ws.ws_col = atoi(col);
ws.ws_xpixel = 0;
ws.ws_ypixel = 0;
if (ioctl(STDOUT_FILENO, TIOCSWINSZ, &ws) == 0) {
printf("Terminal resized to %d x %d\n", ws.ws_row, ws.ws_col);
} else {
perror("resize failed");
}
}
void cmd_help() { printf("Built-ins: ls, cd, pwd, cat, sz, poweroff, reboot\n"); }