I am writing a c library but before I want to test the functions. So, I do the following:
int main(void)
{
GString *msg = NULL;
msg = g_string_sized_new(256);
printf ("Insert a string (255 characters at most): ");
do_fgets((char *) msg->str, (size_t) msg->len, stdin);
printf("msg->allocated_len = %u \n", (size_t) msg->allocated_len);
printf("msg->len = %u \n", (size_t) msg->len);
return 0;
}
the compile is ok, but the program prints the following: msg->allocated_len = 512 msg->len = 0
Why this? Is there any other way to get interactive input from the user using glib functions?
I'll be grateful if somebody could help me!
I'm assuming the do_fgets
is your own function wrapping fgets
, anyway...
Your code is failing since it is trying to read 0 bytes (the initial value of msg->len
). Additionally, msg->len
is never updated (it is passed to do_fgets
by value).
Resurection. I think I've found the solution to my question. What I did is to read the input to a buffer and then assign the buffer to the struct member src an everything is ok: That's the code roughly:
int main(void)
{
GString *msg = NULL;
gchar *p;
gchar buf[256];
msg = g_string_sized_new(256);
printf ("Enter a message (255 characters at most): ");
p = fgets(buf, sizeof(buf), stdin);
g_string_assign(msg, buf);
printf("msg->str = [%s] \n", (char *) msg->str);
printf("msg->len = %u \n", (size_t) msg->len);
printf("msg->allocated_len = %u \n", (size_t) msg->allocated_len);
return 0;
}
So it prints out:
msg->str = [this is my message]
msg->len = 19
msg->allocated_len = 512
The only strange is why the allocated_len is 512 instead of 256. Thanks to everyone for the reply...
Resurrection, debugging led me to the next solution. Thank you Hasturkun for your help, I wanted to post my answer since yesterday but new members cannot answer their questions before 8 hours pass. The solution is this:
int main(void)
{
GString *msg = NULL;
gchar *p;
gchar buf[256];
msg = g_string_sized_new(256);
printf ("Enter a message (255 characters at most): ");
p = fgets(buf, sizeof(buf), stdin);
g_string_assign(msg, buf);
printf("msg->str = [%s] \n", (char *) msg->str);
printf("msg->len = %u \n", (size_t) msg->len);
printf("msg->allocated_len = %u \n", (size_t) msg->allocated_len);
}
And it prints out everything very well... Thank you all for your comments!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.