C言語で
コマンドライン上から入力された文字列を取得したいと考えたとき、
C言語上ではgetchar()やgetc()などの関数しか存在しなかったので、command line上で
確かに入力した文字列を一字一句取得するため以下のような関数をトレーニングも兼ねて書いた。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned char* get_string_from_cli(unsigned char* input) {
unsigned char* temp = NULL;
unsigned char c;
input = malloc(1 * sizeof(char));
if (input == NULL) {
printf("ヒープへのメモリ確保に失敗");
return("");
}
int index = 0;
while(c = getchar()) {
// 取得内容が改行文字だった場合入力終了
if (c == '\n') {
input[index] = 0;
break;
}
input[index] = c;
index++;
temp = realloc(input, (index + 1) * sizeof(char));
if (temp == NULL) {
printf("reallocによるメモリ拡充に失敗");
return ("");
}
if (temp != input ) {
input = temp;
}
}
return (input);
}
int main () {
unsigned char *string_you_input = NULL;
// 特定の文字列を入力するまでCLI上ではループさせる
while (1) {
printf("Input any string you want to ensure:");
string_you_input = get_string_from_cli(string_you_input);
printf("It you inputed is ... => %s", string_you_input);
if (strncmp(string_you_input, "exit", strlen("exit")) == 0) {
printf("Command Lineを終了します。");
exit(0);
}
}
return (0);
}
入力受付終了は[exit]と入力するとループから抜け
アプリケーションを終了することができます。