0
我目前在一個系統軟件類中,我們的最終項目是實現一個簡單的unix像shell環境和具有分層目錄結構的文件系統。我們已經完成了向用戶請求諸如'cd xxx'或'ls'之類的命令的簡單部分。一旦每個命令被調用,它就會進入一個函數。我知道我需要一個像目錄和文件的數據結構樹,但我不知道從哪裏開始。我知道父母只能是一個目錄。該目錄有一個名稱並可以帶有其他目錄和文件。一個文件只有一個名字。我如何去實現這種類型的代碼?這裏是我現在所擁有的:unix像文件系統的目錄結構
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
void makeFS(){
printf("You created and formatted a new filesystem.\n");
}
void listDir(){
printf("Listing all entries in current directory...\n");
}
void exitShell(){
printf("Adios amigo.\n");
exit(0);
}
void makeDir(char name[50]){
printf("Directory [%s] created at !\n", name);
}
void remDir(char cmd[50]){
printf("You entered %s \n", cmd);
}
void changeDir(char *nextName){
printf("Changed directory path to %s\n", nextName);
}
void status(char cmd[50]){
printf("You entered %s \n", cmd);
}
void makeFile(char cmd[50]){
printf("You entered %s \n", cmd);
}
void remFile(char cmd[50]){
printf("You entered %s \n", cmd);
}
int main(int argc, char *argv[]){
char cmd[50];
const char spc[50] = " \n";
char *file, *dir;
char *tok, *nextName;
while (1){
printf("Russ_John_Shell> ");
fgets(cmd, 50, stdin);
//Tokenizes string to determine what command was inputed as well as any file/directory name needed
tok = strtok(cmd, spc);
nextName = strtok(NULL, spc);
//Checks to see whether the string has a file/directory name after the command
if (nextName == NULL){
//mkfs command
if (strcmp(cmd, "mkfs") == 0){
makeFS();
}
//exit command
else if (strcmp(cmd, "exit") == 0){
exitShell();
}
//ls command
else if (strcmp(cmd, "ls") == 0){
listDir();
}
//command not recognized at all
else {
printf("Command not recognized.\n");
}
}
else {
//mkdir command
if (strcmp(cmd, "mkdir") == 0){
makeDir(nextName);
}
//rmdir command
else if (strcmp(cmd, "rmdir") == 0){
remDir(cmd);
}
//cd command
else if (strcmp(cmd, "cd") == 0){
changeDir(nextName);
}
//stat command
else if (strcmp(cmd, "stat") == 0){
status(cmd);
}
//mkfile command
else if (strcmp(cmd, "mkfile") == 0){
makeFile(cmd);
}
//rmfile command
else if (strcmp(cmd, "rmfile") == 0){
remFile(cmd);
}
//command not recognized at all
else {
printf("Command not recognized.\n");
}
}
}
}
首先,擺脫所有'cmd [50]'聲明。定義一個參數,如'#define CMDLEN 50'。 – paulsm4
@ paulsm4或者更好的是,使用'std :: string',因爲它被標記爲C++。 – MrEricSir