2014年02月08日 星期六 09:17
GLib库 File Utilities 模块提供了操作文件相关的一些API,例如获取文件内容,判断文件是否存在,将文件映射到内存等等。
下面的代码实例结合了上一期的Checksum算法,演示了File Utilities的一些使用方法。
#include <stdio.h>
#include <glib.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char **argv) {
if(argc != 3) {
fprintf(stderr,
"usage: %s type(md5|sha1|sha256) filename\n",argv[0]);
return -1;
}
GChecksumType type;
if(strcmp("md5",argv[1]) == 0) {
type=G_CHECKSUM_MD5;
} else if (strcmp("sha1",argv[1]) == 0) {
type=G_CHECKSUM_SHA1;
} else if (strcmp("sha256",argv[1]) == 0) {
type=G_CHECKSUM_SHA256;
} else {
type=G_CHECKSUM_MD5;
}
char *filename=argv[2];
gchar *contents;
gsize length;
g_file_get_contents(filename,&contents,&length,NULL);
char *result=g_compute_checksum_for_data(type,contents,length);
printf("%s\n",result);
GMappedFile *mfile;
mfile=g_mapped_file_new(filename,FALSE,NULL);
length=g_mapped_file_get_length(mfile);
contents=g_mapped_file_get_contents(mfile);
result=g_compute_checksum_for_data(type,contents,length);
printf("%s\n",result);
g_mapped_file_unref(mfile);
return 0;
}
参考资料:
https://developer.gnome.org/glib/2.39/glib-File-Utilities.html
Zeuux © 2025
京ICP备05028076号