2010-11-13 125 views
1

我試圖學習glib/gtk。我寫了很少的代碼打印目錄中的文件,如果它們是普通文件,則分配「f」;如果它們是目錄,則分配「d」。問題是如果。它總是得到錯誤的值並將「f」附加到文件名中。glib中g_file_test的問題

#include <glib.h> 
#include <glib/gstdio.h> 
#include <glib/gprintf.h> 

int main() 
{ 
    GDir* home = NULL; 
    GError* error = NULL; 
    gchar* file = "a"; 

    home = g_dir_open("/home/stamp", 0, &error); 
    while (file != NULL) 
    { 
     file = g_dir_read_name(home); 
     if (g_file_test(file, G_FILE_TEST_IS_DIR)) 
     { 
      g_printf("%s: d\n", file); 
     } else { 
      g_printf("%s: f\n", file); 
     } 
    } 
} 

回答

3

g_dir_read_name僅返回目錄/文件名。您需要建立完整路徑才能使用g_file_test進行測試。你可以使用g_build_filename

int main() 
{ 
    GDir* home = NULL; 
    GError* error = NULL; 
    gchar* file = "a"; 

    home = g_dir_open("/home/stamp", 0, &error); 
    while (file != NULL) 
    { 
     file = g_dir_read_name(home); 

     gchar* fileWithFullPath; 
     fileWithFullPath = g_build_filename("/home/stamp", file, (gchar*)NULL); 
     if (g_file_test(fileWithFullPath, G_FILE_TEST_IS_DIR)) 
     { 
      g_printf("%s: d\n", file); 
     } 
     else 
     { 
      g_printf("%s: f\n", file); 
     } 
     g_free(fileWithFullPath); 
    } 
    g_dir_close(home); 
}
+0

感謝它的工作 – GeekDaddy 2010-11-13 22:16:26

+1

不要忘了'g_free(fileWithFullPath);'。 – 2010-11-13 22:21:05

+0

@mu太短,謝謝! – swatkat 2010-11-13 22:25:44