Last active
May 20, 2021 15:54
-
-
Save daerich/ee7e51a0b826637282e0982d4ef0f618 to your computer and use it in GitHub Desktop.
read from stdin(my own template)(may be horrible)
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
static char* addread(char* buf,char r, int length){ | |
char * res=malloc((length+1) * sizeof(char)); | |
if(res == NULL){ | |
fprintf(stderr,"Malloc Error\n"); /* Quit on malloc*/ | |
exit(1); | |
} | |
for(int x=0;x < length ;x++){ | |
res[x]=buf[x]; | |
} | |
res[length]=r; /* Those are offsets FFS */ | |
printf("In buffer:%d\n",res[length]); | |
if(length > 0) | |
free(buf); | |
return res; | |
} | |
int | |
main(int argc, char**argv){ | |
char * buf; | |
char ch; | |
int length; | |
for(length = 0;(ch=fgetc(stdin)) != EOF;length++){ | |
if((buf=addread(buf,ch,length)) == NULL){ | |
fprintf(stderr,"Read Error\n"); | |
return 1; /* Quit on bad read */ | |
} | |
} | |
// puts("eof"); useless logging | |
buf=addread(buf,'\0',length); | |
printf("Result:%s,%d\n",buf,strlen(buf)); | |
free(buf); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment