這裏是我的代碼和系統調用,當只有一個單詞之間沒有空格或任何內容(如enter ...)時。fgets函數不讀取輸入中的第一個字符
例如,當我用「PWD」的號召作品,但是當我使用類似ls -l
或讓我們說「CD文件1文件2」,它會清除第一個字符,並沒有考慮到空間後帳戶什麼。
所以當我寫「cd file1 file2」時只剩下「cd」的「d」。我能做些什麼來防止這種情況發生?
#include <stdlib.h>
#include <stdio.h>
#include "Expert_mode.h"
void Expert_mode()
{
printf("Your are now in Expert mode, You are using a basic Shell (good luck) \nWe added the commands 'read_history', 'leave' and 'Easter_egg'. \n");
int a = 0;
while(a == 0)
{
char* line;
getchar();
printf("Choose a command : \n");
line = malloc(100*sizeof(char));
fgets(line, 100, stdin);
if(strcoll(line, "leave") == 0)
{
a = 1;
}
else if(strcoll(line, "read_history") == 0)
{
//read_history();
}
else if(strcoll(line, "Easter_egg") == 0)
{
// Easter_egg();
}
else
{
system(line);
}
}
}
如果你要分配一個固定大小的緩衝區,爲什麼不使用數組?那麼你將不會有內存泄漏。 –