Last active
September 29, 2023 14:09
-
-
Save Dwyriel/b0feaf16b04ef0c33096c5ba5a1c34a4 to your computer and use it in GitHub Desktop.
Read input of any length in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| char *inputString(FILE* fp, size_t chunk){ | |
| if(chunk < 1) | |
| chunk = 1; | |
| char *str; | |
| int ch; | |
| size_t len = 0; | |
| str = realloc(NULL, sizeof(*str) * chunk); | |
| if(!str)return str; | |
| while(EOF!=(ch=fgetc(fp)) && ch != '\n'){ | |
| str[len++]=ch; | |
| if(len == chunk){ | |
| str = realloc(str, sizeof(*str)*(chunk+=16)); | |
| if(!str)return str; | |
| } | |
| } | |
| str[len++]='\0'; | |
| return realloc(str, sizeof(*str)*len); | |
| } | |
| char* readinput() | |
| { | |
| const int CHUNK = 2;//chunk must be at minimum 2 | |
| char* input = NULL; | |
| char tempbuf[CHUNK]; | |
| size_t inputlen = 0, templen = 0; | |
| do { | |
| fgets(tempbuf, CHUNK, stdin); | |
| templen = strlen(tempbuf); | |
| input = realloc(input, inputlen+templen+1); | |
| strcpy(input+inputlen, tempbuf); | |
| inputlen += templen; | |
| } while (templen==CHUNK-1 && tempbuf[CHUNK-2]!='\n'); | |
| return input; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment