私は自分の質問に対する答えをどこでも探しましたが、私の問題に対する確かな答えはまだ見つかりません。
私は現在、特にUNIXコマンドラインを対象にCでプログラムを作成中です(開発環境としてLinuxを使用していますが、このプログラムを可能な限り移植可能にしたいと考えています)。現在、ユーザー入力を求める基本的なシェルがあります。次に、ユーザーがコマンドを入力すると、そのコマンドがそれに応じて処理されます。これが私がこれまでに持っているコードです:
/* Main.c */
int main(int argc, char **argv)
{
while (TRUE)
{
display_prompt();
get_command();
}
return 0;
}
/* Main.h */
void get_command()
{
/*
* Reads in a command from the user, outputting the correct response
*/
int buffer_size = 20;
char *command = (char*) malloc(sizeof(char) * buffer_size);
if (command == NULL)
{
return_error("Error allocating memory");
}
fgets(command, buffer_size, stdin);
if (command[strlen(command) - 1] == '\n')
{
puts("It's inside the buffer.");
}
else
{
puts("It's not inside the buffer.");
}
free(command);
}
私の最初の考えは、\n
文字をチェックして、それがの中に収まるかどうか、そして割り当てられたメモリを拡張するためのデータが収まらないかどうかを確認buffer_size
することでした。realloc()
ただし、文字列を入力した後、残りのデータをにrealloc()
追加するにはどうすればよいですか?stdin
command