Voici une source qui permet de connaître l'encodage d'un
fichier texte. Comme il n'existe aucune méta-donnée dans
les fichiers texte, nous sommes obligés de tester un à un
différents encodages jusqu'à ce que la covertion réussisse.
Dans ce code, je me contente de tester UTF-8 et ISO-8859-15
qui sont les plus répendus.
encoding.h | # ifndef H_NJ_ENCODING_11122007161145
# define H_NJ_ENCODING_11122007161145
# include <glib.h>
G_BEGIN_DECLS
const gchar * encoding_get_charset (const gchar * );
G_END_DECLS
# endif
|
encoding.c | # include "encoding.h"
# include <stdlib.h>
# include <string.h>
static const gchar * charsets[] = { " UTF-8 " , " ISO-8859-15 " , NULL } ;
static gboolean test_encoding (const gchar * filename, const gchar * charset)
{
gboolean valid = FALSE;
if (filename ! = NULL )
{
gchar * content = NULL ;
g_file_get_contents (filename, & content, NULL , NULL );
if (content ! = NULL )
{
gchar * convert = NULL ;
gsize bytes_read = 0 ;
convert = g_convert (content, - 1 , " UTF-8 " , charset, & bytes_read, NULL ,
NULL );
if (convert ! = NULL )
{
if (bytes_read = = strlen (content))
{
valid = TRUE;
}
free (convert), convert = NULL ;
}
free (content), content = NULL ;
}
}
return valid;
}
const gchar * encoding_get_charset (const gchar * filename)
{
gint i;
for (i = 0 ; charsets[i] ! = NULL ; i+ + )
{
if (test_encoding (filename, charsets[i]))
{
break ;
}
}
return charset[i];
}
|
|