2013-04-12 3 views
4

J'essaie d'utiliser GJS et plus précisément pour lire un fichier texte de manière synchrone. Voici un exemple d'une la fonction asynchrone pour la lecture du fichierGJS lit le fichier de manière synchrone

gio-cat.js J'ai trouvé comment procéder avec des semences en utilisant la fonction suivante:

function readFile(filename) { 
    print(filename); 
    var input_file = gio.file_new_for_path(filename); 
    var fstream = input_file.read(); 
    var dstream = new gio.DataInputStream.c_new(fstream); 
    var data = dstream.read_until("", 0); 
    fstream.close(); 
    return data; 
} 

mais malheureusement, il ne fonctionne pas avec GJS. Quelqu'un peut-il m'aider?

Répondre

1

Comme je l'utilise GJS pour le développement applets cannelle, je l'habitude d'utiliser la fonction get_file_contents_utf8_sync pour lire les fichiers texte:

const Cinnamon = imports.gi.Cinnamon; 

let fileContent = Cinnamon.get_file_contents_utf8_sync("file path"); 

Si vous avez cannelle installé et que vous acceptez de les utiliser, il répond à votre question.
Sinon, voici le code C de la fonction get_file_contents_utf8_sync, en espérant que cela vous aidera:

char * cinnamon_get_file_contents_utf8_sync (const char *path, GError **error) 
{ 
    char *contents; 
    gsize len; 
    if (!g_file_get_contents (path, &contents, &len, error)) 
    return NULL; 
    if (!g_utf8_validate (contents, len, NULL)) 
    { 
     g_free (contents); 
     g_set_error (error, 
        G_IO_ERROR, 
        G_IO_ERROR_FAILED, 
        "File %s contains invalid UTF-8", 
        path); 
     return NULL; 
    } 
    return contents; 
} 

Cinnamon source code

1

Voici une solution qui fonctionne avec seulement Gio.

function readFile(filename) { 
    let input_file = Gio.file_new_for_path(filename); 
    let size = input_file.query_info(
     "standard::size", 
     Gio.FileQueryInfoFlags.NONE, 
     null).get_size(); 
    let stream = input_file.open_readwrite(null).get_input_stream(); 
    let data = stream.read_bytes(size, null).get_data(); 
    stream.close(null); 
    return data; 
} 
0

Essayez de remplacer

new gio.DataInputStream.c_new(fstream); 

avec

gio.DataInputStream.new(fstream); 

il a travaillé pour moi

0

GLib a la fonction d'aide GLib.file_get_contents(String fileName) pour lire les fichiers de manière synchrone:

const GLib = imports.gi.GLib; 
//... 
let fileContents = String(GLib.file_get_contents("/path/to/yourFile")[1]); 
Questions connexes