#include #include #include #include #include #include #include #define STDIN 0 #define STDOUT 1 static void print(const char* s) { write(STDOUT, s, strlen(s)); } static void touch(const char* path) { int fd = open(path, O_CREAT | O_WRONLY, 0644); if (fd < 0) { print("touch: cannot create file\n"); return; } close(fd); } static void ls(const char* path) { struct dirent* entry; DIR* dir = opendir(path ? path : "."); if (!dir) { print("ls: cannot open directory\n"); return; } while ((entry = readdir(dir)) != NULL) { // skip . and .. if (entry->d_name[0] == '.' && (entry->d_name[1] == '\0' || (entry->d_name[1] == '.' && entry->d_name[2] == '\0'))) continue; print(entry->d_name); print("\n"); } closedir(dir); } static void readline(char* buf, size_t max) { size_t i = 0; while (i < max - 1) { char c; ssize_t n = read(STDIN, &c, 1); if (n <= 0) continue; if (c == '\n') break; if (c == '\b') { if (i > 0) i--; continue; } buf[i++] = c; } buf[i] = '\0'; } static void cat(const char* path) { char buf[256]; int fd = open(path, O_RDONLY); if (fd < 0) { print("cat: cannot open file\n"); return; } ssize_t n = read(fd, buf, sizeof(buf)); close(fd); if (n > 0) write(STDOUT, buf, (size_t)n); } int main(void) { const char* path = "/qwerty.txt"; const char* msg = "Suki Suki Daisuki Kekkon Shiyo, my honey!"; char buf[128]; int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); write(fd, msg, strlen(msg)); close(fd); fd = open(path, O_RDONLY); ssize_t n = read(fd, buf, sizeof(buf)); close(fd); if (n > 0) write(STDOUT, buf, (size_t)n); char line[128]; while (1) { print("> "); readline(line, sizeof(line)); if (strcmp(line, "exit") == 0) break; if (line[0] == 'c' && line[1] == 'a' && line[2] == 't' && line[3] == ' ') { cat(&line[4]); continue; } if (line[0] == 't' && line[1] == 'o' && line[2] == 'u' && line[3] == 'c' && line[4] == 'h' && line[5] == ' ') { touch(&line[6]); continue; } if (line[0] == 'l' && line[1] == 's') { if (line[2] == ' ') ls(&line[3]); else ls(NULL); continue; } if (line[0] != '\0') print("Unknown command\n"); } return 0; }