Skip to content

Instantly share code, notes, and snippets.

@tats-u
Created March 26, 2018 12:09
Show Gist options
  • Save tats-u/22aa8a89de5c8c88b8731ecefb36fcd6 to your computer and use it in GitHub Desktop.
Save tats-u/22aa8a89de5c8c88b8731ecefb36fcd6 to your computer and use it in GitHub Desktop.
長さ無制限のgets
#include <stdio.h>
#include <stdlib.h>
//1行の入力を受け付ける関数。
//字数無制限。
//-1→失敗 0→正常 1→入力なし
//利用方法: gets_line(&pt) (pt: char* (=NULL))
//使用したポインタは必ず開放してください
#define GETS_LINE_INITIAL_LEN 64
int gets_line(char **pt) {
int times = 0, len = 0, ch;
//現在文字データが入っているなら解放
if(*pt != NULL) free(*pt);
//初期サイズの領域を確保
*pt = (char *)malloc(GETS_LINE_INITIAL_LEN);
//確保失敗
if(*pt == NULL) return -1;
//文字入力受け付けループ(改行文字まで)
while((ch = getchar()) != '\n') {
//領域が溢れそうなら拡張
if(len == (GETS_LINE_INITIAL_LEN << times)) {
*pt = (char *)realloc(*pt, GETS_LINE_INITIAL_LEN << ++times);
if(*pt == NULL) return -1;
}
//文字を1文字取得して書き込み
*(*pt + len++) = (char)ch;
}
//末尾のヌル文字を書き込むのに領域が足りなければ拡張
if(len == (GETS_LINE_INITIAL_LEN << times)) {
*pt = (char *)realloc(*pt, GETS_LINE_INITIAL_LEN << ++times);
if(*pt == NULL) return -1;
}
//末尾にヌル文字挿入
*(*pt + len) = 0;
//何も入力されていない
if(len == 0) return 1;
//正常
return 0;
}
int main() {
char *str = NULL;
int res;
puts("文字を入力しろ");
res = gets_line(&str);
if(res == -1) {
puts("(アカン)");
return 2;
}
if(res == 0) {
puts("入力した文字は↓");
puts(str);
} else {
puts("入力なし");
}
free(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment