使用glib读写文件
时间: 2023-10-15 11:05:34 浏览: 56
使用GLib可以方便地进行文件的读写操作。下面是一个简单的示例代码,演示了如何使用GLib读取文件内容并将其输出到控制台上:
```c
#include <stdio.h>
#include <glib.h>
int main(void) {
gchar *file_name = "test.txt";
gchar *file_contents = NULL;
gsize file_size = 0;
if (g_file_get_contents(file_name, &file_contents, &file_size, NULL)) {
printf("File contents:\n%s\n", file_contents);
g_free(file_contents);
} else {
printf("Failed to read file %s\n", file_name);
}
return 0;
}
```
上面的代码首先定义了一个文件名和一个用于存储文件内容的变量。然后,使用`g_file_get_contents()`函数读取文件内容,并将其存储在`file_contents`变量中。如果成功读取文件,则将文件内容输出到控制台,并释放`file_contents`变量。如果读取文件失败,则输出错误消息。
类似地,使用`g_file_set_contents()`函数可以将数据写入文件中。下面是一个简单的示例代码,演示了如何使用GLib将字符串写入文件中:
```c
#include <stdio.h>
#include <glib.h>
int main(void) {
gchar *file_name = "test.txt";
gchar *file_contents = "Hello, world!\n";
gsize file_size = strlen(file_contents);
if (g_file_set_contents(file_name, file_contents, file_size, NULL)) {
printf("File written successfully.\n");
} else {
printf("Failed to write file %s\n", file_name);
}
return 0;
}
```
上面的代码首先定义了一个文件名和一个要写入文件中的字符串。然后,使用`g_file_set_contents()`函数将字符串写入文件中。如果成功写入文件,则输出成功消息。否则,输出错误消息。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)