使用 GIO 处理文件

sri*_*sri 1 c gtk file-handling gio

我需要打开一个文件来读取内容并将其内容显示在屏幕上。这应该使用 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;
}
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Tin*_*ing 5

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

#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;
}
Run Code Online (Sandbox Code Playgroud)