Skip to content

Instantly share code, notes, and snippets.

@daerich
Last active May 20, 2021 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daerich/ee7e51a0b826637282e0982d4ef0f618 to your computer and use it in GitHub Desktop.
Save daerich/ee7e51a0b826637282e0982d4ef0f618 to your computer and use it in GitHub Desktop.
read from stdin(my own template)(may be horrible)
#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