Use Gio for random_line()

This commit is contained in:
TingPing 2014-08-26 22:27:40 -04:00 committed by Patrick Griffis
parent 7cf631f93c
commit c0c2668c10

View File

@ -78,40 +78,72 @@ notc_msg (struct session *sess)
static char * static char *
random_line (char *file_name) random_line (char *file_name)
{ {
FILE *fh; GFile *file;
char buf[512]; char *data, *p, *ret = NULL;
int lines, ran; int lines = 0, ran;
gsize len;
if (!file_name[0]) if (!file_name[0])
goto nofile; return g_strdup ("");
fh = hexchat_fopen_file (file_name, "r", 0); file = hexchat_open_gfile (file_name);
if (!fh)
if (!g_file_query_exists (file, NULL))
{ {
nofile:
/* reason is not a file, an actual reason! */ /* reason is not a file, an actual reason! */
return g_strdup (file_name); return g_strdup (file_name);
} }
/* count number of lines in file */ if (!g_file_load_contents (file, NULL, &data, &len, NULL, NULL))
lines = 0;
while (fgets (buf, sizeof (buf), fh))
lines++;
if (lines < 1)
goto nofile;
/* go down a random number */
rewind (fh);
ran = RAND_INT (lines);
do
{ {
fgets (buf, sizeof (buf), fh); g_object_unref (file);
lines--; return g_strdup (file_name);
} }
while (lines > ran);
fclose (fh); g_object_unref (file);
return g_strdup (buf);
/* count number of lines in file */
p = data;
while (p != data + len)
{
if (*p == '\n')
lines++;
p++;
}
if (!lines)
{
g_free (data);
return g_strdup (file_name);
}
/* create random number */
ran = RAND_INT (lines);
/* get that random line */
p = data;
while (p != data + len)
{
if (*p == '\n')
{
if (!--ran)
{
char *end;
end = strchr (++p, '\n');
*end = '\0';
ret = g_strdup (p);
break;
}
}
p++;
}
g_free (data);
if (ret)
return ret;
else
return g_strdup (file_name);
} }
void void