意外と任意の長さの文字列を取りたい場面って有りますよね。
ネットに意外と情報がないので全然綺麗じゃないですがちょっと書いてみました。
#include <stdio.h> #include <stdlib.h> char* readLine(); char* prompt(char *s); int main(int argc, char **argv) { char *line; line = prompt("$ "); printf("Inputed Line: %s\n",line); free(line); return 0; } char* readLine() { char *line, *line1, *line2; char ch; int currentSize = 128; int currentReadSize = 0; line1 = (char *)malloc(currentSize); line = line1; while( (ch = getchar()) != EOF ) { if(ch == '\n') { break; } if((currentReadSize + 1) >= currentSize) { if(line1 != NULL) { line2 = (char *)realloc(line1,currentSize + 10); if(line2 == NULL) { fprintf(stderr,"Realloc Error!!\n"); free(line1); exit(1); } line1 = NULL; line = line2; } else if(line2 != NULL) { line1 = (char *)realloc(line2,currentSize + 10); if(line1 == NULL) { fprintf(stderr,"Realloc Error!!\n"); free(line2); exit(1); } line2 = NULL; line = line1; } else { fprintf(stderr,"Something happen.\n"); exit(1); } currentSize += 10; } line[currentReadSize++] = ch; } return line; } char* prompt(char *s) { char *line; printf("%s",s); return readLine(); }