~ubuntu-branches/ubuntu/saucy/dosfstools/saucy-proposed

« back to all changes in this revision

Viewing changes to src/charconv.c

  • Committer: Package Import Robot
  • Author(s): Daniel Baumann
  • Date: 2013-03-10 19:58:06 UTC
  • mfrom: (4.1.13 sid)
  • Revision ID: package-import@ubuntu.com-20130310195806-vywfbcwucgagcynz
Tags: 3.0.16-2
Removing all references to my old email address.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include "charconv.h"
 
2
#include <iconv.h>
 
3
#include <langinfo.h>
 
4
#include <locale.h>
 
5
#include <stdio.h>
 
6
 
 
7
static iconv_t iconv_init_codepage(int codepage)
 
8
{
 
9
    iconv_t result;
 
10
    char codepage_name[16];
 
11
    snprintf(codepage_name, sizeof(codepage_name), "CP%d", codepage);
 
12
    result = iconv_open(nl_langinfo(CODESET), codepage_name);
 
13
    if (result == (iconv_t) - 1)
 
14
        perror(codepage_name);
 
15
    return result;
 
16
}
 
17
 
 
18
static iconv_t dos_to_local;
 
19
 
 
20
/*
 
21
 * Initialize conversion from codepage.
 
22
 * codepage = -1 means default codepage.
 
23
 * Returns 0 on success, non-zero on failure
 
24
 */
 
25
static int init_conversion(int codepage)
 
26
{
 
27
    static int initialized = -1;
 
28
    if (initialized < 0) {
 
29
        initialized = 1;
 
30
        if (codepage < 0)
 
31
            codepage = DEFAULT_DOS_CODEPAGE;
 
32
        setlocale(LC_ALL, "");  /* initialize locale */
 
33
        dos_to_local = iconv_init_codepage(codepage);
 
34
        if (dos_to_local == (iconv_t) - 1 && codepage != DEFAULT_DOS_CODEPAGE) {
 
35
            printf("Trying to set fallback DOS codepage %d\n",
 
36
                   DEFAULT_DOS_CODEPAGE);
 
37
            dos_to_local = iconv_init_codepage(DEFAULT_DOS_CODEPAGE);
 
38
            if (dos_to_local == (iconv_t) - 1)
 
39
                initialized = 0;        /* no conversion available */
 
40
        }
 
41
    }
 
42
    return initialized;
 
43
}
 
44
 
 
45
int set_dos_codepage(int codepage)
 
46
{
 
47
    return init_conversion(codepage);
 
48
}
 
49
 
 
50
int dos_char_to_printable(char **p, unsigned char c)
 
51
{
 
52
    char in[1] = { c };
 
53
    char *pin = in;
 
54
    size_t bytes_in = 1;
 
55
    size_t bytes_out = 4;
 
56
    if (!init_conversion(-1))
 
57
        return 0;
 
58
    return iconv(dos_to_local, &pin, &bytes_in, p, &bytes_out) != -1;
 
59
}