C, GLib: Is there a method to get the size - can be applied to text file, binary file, folder, and symbolic link in common?
// gcc z.c -o z $(pkg-config --cflags --libs gtk+-2.0)
#include <string.h>
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
struct tst
{
GtkWidget *win, *vb, *ent, *btn, *lbl;
GtkAccelGroup *acc;
GClosure *cls;
};
static void print_val(st开发者_开发技巧ruct tst *prg)
{
const char *nam = gtk_entry_get_text(GTK_ENTRY(prg->ent));
char *cont;
g_file_get_contents(nam, &cont, NULL, NULL);
int siz = strlen(cont);
g_printf("%d\n", siz);
}
static void window_new()
{
struct tst *prg = g_new0(struct tst, 1);
prg->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
prg->vb = gtk_vbox_new(TRUE, 0);
prg->ent = gtk_entry_new();
prg->btn = gtk_button_new_with_label("Print!");
prg->lbl = gtk_label_new("Enter the string.");
gtk_container_add(GTK_CONTAINER(prg->win), GTK_WIDGET(prg->vb));
gtk_box_pack_start(GTK_BOX(prg->vb), GTK_WIDGET(prg->ent), FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(prg->vb), GTK_WIDGET(prg->btn), FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(prg->vb), GTK_WIDGET(prg->lbl), FALSE, FALSE, 0);
g_signal_connect_swapped(prg->win, "destroy", G_CALLBACK(gtk_main_quit), NULL);
g_signal_connect_swapped(prg->btn, "clicked", G_CALLBACK(print_val), prg);
gtk_window_set_title(GTK_WINDOW(prg->win), "Enter the string");
gtk_widget_show_all(GTK_WIDGET(prg->win));
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
window_new();
gtk_main();
return 0;
}
With g_file_get_contents(), at least in this example program, I can get the size of text file, but I can't get the size of binary file, folder, and symbolic link.
When I try to get the size of binary file with that, it gives the weird value, not the size of binary file.
When I try to get the size of folder with that, it crashes with segmentation fault.
And when I try to get the size of symbolic link with that, it gives the size of regular file which link refers, not link itself.
Is there a method to get the size - can be applied to text file, binary file, folder, and symbolic link in common?
The usual way is
#include <sys/stat.h>
struct stat st;
if (lstat(filepath, &st) == -1) {
perror(filepath);
exit(1);
}
filesize = st.st_size;
Note that with lstat()
the size reported will be the size of the symlink itself, not the object it references; if you didn't actually want the symlink's own size, use stat()
instead.
You might have to use realpath() to resolve the symbolic links. After that you could just use fstat().
struct stat *s;
int fd;
s = malloc(sizeof(struct stat));
fd = open("somefile", O_RDONLY);
fstat(fd, s);
printf("%d\n", s->st_size);
精彩评论