J
jaso
I've written a function that reads multiple
lines and puts it in a string.
What do you think of it, is it correct?
Thanks!
#define BUFSIZE 1024
int read_multiline(char **str)
{
char inputbuf[BUFSIZE];
char *tmp;
size_t size = BUFSIZE;
*str = malloc(size);
if (*str == NULL)
return -1;
(*str)[0] = '\0';
fgets(inputbuf, BUFSIZE, stdin);
while (inputbuf[0] != '\n') {
/* Allocate more memory if needed */
if (strlen(*str) + strlen(inputbuf) >= size) {
size += BUFSIZE;
tmp = realloc(*str, size);
if (tmp == NULL) {
free(*str);
return -1;
}
else
*str = tmp;
}
strcat(*str, inputbuf);
fgets(inputbuf, BUFSIZE, stdin);
}
return 0;
}
lines and puts it in a string.
What do you think of it, is it correct?
Thanks!
#define BUFSIZE 1024
int read_multiline(char **str)
{
char inputbuf[BUFSIZE];
char *tmp;
size_t size = BUFSIZE;
*str = malloc(size);
if (*str == NULL)
return -1;
(*str)[0] = '\0';
fgets(inputbuf, BUFSIZE, stdin);
while (inputbuf[0] != '\n') {
/* Allocate more memory if needed */
if (strlen(*str) + strlen(inputbuf) >= size) {
size += BUFSIZE;
tmp = realloc(*str, size);
if (tmp == NULL) {
free(*str);
return -1;
}
else
*str = tmp;
}
strcat(*str, inputbuf);
fgets(inputbuf, BUFSIZE, stdin);
}
return 0;
}