1

我需要打开一个文件来读取内容并在屏幕上显示其内容。这应该使用 GIO 文件处理来完成。我正在阅读本教程,但作为一种实践,我需要使用 GIO 来编写以下 c 代码的代码。在 c 中,程序可以是:

#include<stdio.h>
#include<string.h>
int main()
{

  FILE *fp;
  char temp[1000];
  if(fp=fopen("locations.txt", "r") != NULL)
   {
     fgets(temp, 1000, fp);
     printf("%s", temp[1000]);
    }
 fclose(fp);
return 0;
}

提前致谢。

4

2 回答 2

4

这是您当前拥有的确切行为的粗略近似值。可以通过错误消息、一次读取一行等来改进它。

#include <gio/gio.h>

int main(void)
{
    g_autoptr(GFile) file = g_file_new_for_path("locations.txt");
    g_autoptr(GFileInputStream) in = g_file_read(file, NULL, NULL);
    if(!in)
        return 1;

    gssize read;
    char temp[1000];

    while (TRUE)
    {
      read = g_input_stream_read(G_INPUT_STREAM(in), temp, G_N_ELEMENTS(temp) - 1, NULL, NULL);
      if (read > 0)
      {
          temp[read] = '\0';
          g_print("%s", temp);
      }
      else if (read < 0)
          return 1;
      else
         break;
    }

    return 0;
}
于 2016-12-01T00:28:51.117 回答
0

我的问题的答案:

#include <gtk/gtk.h>

int main(void)
{
GFile *file = g_file_new_for_path("FINAL_SERVER_URLS.txt");

GFileInputStream *in = g_file_read(file, NULL, NULL);
if(!in)
    return 1;

gssize read;
gchar temp[1000];

while (TRUE)
{
  read = g_input_stream_read(G_INPUT_STREAM(in), temp, G_N_ELEMENTS(temp) - 1, NULL, NULL);
  if (read > 0)
  {
      temp[read] = '\0';
      g_print("%s", temp);
  }
  else if (read < 0)
      return 1;
  else
     break;
}
//g_free(temp);
g_object_unref(file);
g_object_unref(in);
    return 0;
}
于 2016-12-01T10:10:40.450 回答