Input of dynamic size using fgets in C

空扰寡人 提交于 2019-12-23 01:55:25

问题


I want to have a string(can contain spaces) as input. I want to do dynamic allocation. Structure of my program is somewhat like 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 to know how to get input. Is there any way that the second argument of fgets be dynamic?


回答1:


Use getline(3) -instead of fgets(3)- which reads a dynamically allocated line.

typedef struct msgclient {
  ssize_t msglen;
  int msgtype;
  char *cp;
}M1;

then in your 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 the allocated size of the buffer (i.e. msgsize) as an additional field of struct msgclient

addenda:

Notice that you might perhaps consider using GNU readline. It offers edition and completion facilities (when reading from a terminal).



来源:https://stackoverflow.com/questions/22604537/input-of-dynamic-size-using-fgets-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!