linux - Input of dynamic size using fgets in C -
i want have string(can contain spaces) input. want dynamic allocation. structure of program this.
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct msgclient { int msglen; int msgtype; char *cp; }m1; int main() { m1 *m; m=malloc(sizeof(m1)); m->msglen=5; m->msgtype=6; printf("enter\t"); fgets(m->cp,50,stdin); //here // m->cp[strlen(m->cp)]='\0'; printf("\n%d\n%d\n",m->msglen,m->msgtype); fputs(m->cp,stdout); return 0; }
i want know how input. there way second argument of fgets dynamic?
use getline(3) -instead of fgets(3)- reads dynamically allocated line.
typedef struct msgclient { ssize_t msglen; int msgtype; char *cp; }m1;
then in main
function
m1 *m; m=malloc(sizeof(m1)); if (!m) { perror("malloc"); exit(exit_failure); }; m->msglen=0; m->msgtype=6; m->cp = null; printf("enter\t"); fflush(stdout); size_t msgsize = 0; m->msglen = getline(&msg->cp, &msgsize, stdin);
you might consider adding allocated size of buffer (i.e. msgsize
) additional field of struct msgclient
addenda:
notice might perhaps consider using gnu readline. offers edition , completion facilities (when reading terminal).
Comments
Post a Comment