1 /* Convert text in given files from the specified from-set to the to-set.
2 Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
36 #ifdef _POSIX_MAPPED_FILES
37 # include <sys/mman.h>
40 #include <gconv_int.h>
41 #include "iconv_prog.h"
42 #include "iconvconfig.h"
44 /* Get libc version number. */
45 #include "../version.h"
47 #define PACKAGE _libc_intl_domainname
50 /* Name and version of program. */
51 static void print_version (FILE *stream
, struct argp_state
*state
);
52 void (*argp_program_version_hook
) (FILE *, struct argp_state
*) = print_version
;
54 #define OPT_VERBOSE 1000
57 /* Definitions of arguments for argp functions. */
58 static const struct argp_option options
[] =
60 { NULL
, 0, NULL
, 0, N_("Input/Output format specification:") },
61 { "from-code", 'f', "NAME", 0, N_("encoding of original text") },
62 { "to-code", 't', "NAME", 0, N_("encoding for output") },
63 { NULL
, 0, NULL
, 0, N_("Information:") },
64 { "list", 'l', NULL
, 0, N_("list all known coded character sets") },
65 { NULL
, 0, NULL
, 0, N_("Output control:") },
66 { NULL
, 'c', NULL
, 0, N_("omit invalid characters from output") },
67 { "output", 'o', "FILE", 0, N_("output file") },
68 { "silent", 's', NULL
, 0, N_("suppress warnings") },
69 { "verbose", OPT_VERBOSE
, NULL
, 0, N_("print progress information") },
70 { NULL
, 0, NULL
, 0, NULL
}
73 /* Short description of program. */
74 static const char doc
[] = N_("\
75 Convert encoding of given files from one encoding to another.");
77 /* Strings for arguments in help texts. */
78 static const char args_doc
[] = N_("[FILE...]");
80 /* Prototype for option handler. */
81 static error_t
parse_opt (int key
, char *arg
, struct argp_state
*state
);
83 /* Function to print some extra text in the help message. */
84 static char *more_help (int key
, const char *text
, void *input
);
86 /* Data structure to communicate with argp functions. */
87 static struct argp argp
=
89 options
, parse_opt
, args_doc
, doc
, NULL
, more_help
92 /* Code sets to convert from and to respectively. An empty string as the
93 default causes the 'iconv_open' function to look up the charset of the
94 currently selected locale and use it. */
95 static const char *from_code
= "";
96 static const char *to_code
= "";
98 /* File to write output to. If NULL write to stdout. */
99 static const char *output_file
;
101 /* Nonzero if verbose ouput is wanted. */
104 /* Nonzero if list of all coded character sets is wanted. */
107 /* If nonzero omit invalid character from output. */
110 /* Prototypes for the functions doing the actual work. */
111 static int process_block (iconv_t cd
, char *addr
, size_t len
, FILE *output
);
112 static int process_fd (iconv_t cd
, int fd
, FILE *output
);
113 static int process_file (iconv_t cd
, FILE *input
, FILE *output
);
114 static void print_known_names (void) internal_function
;
118 main (int argc
, char *argv
[])
120 int status
= EXIT_SUCCESS
;
124 const char *orig_to_code
;
125 struct charmap_t
*from_charmap
= NULL
;
126 struct charmap_t
*to_charmap
= NULL
;
128 /* Set locale via LC_ALL. */
129 setlocale (LC_ALL
, "");
131 /* Set the text message domain. */
132 textdomain (_libc_intl_domainname
);
134 /* Parse and process arguments. */
135 argp_parse (&argp
, argc
, argv
, 0, &remaining
, NULL
);
137 /* List all coded character sets if wanted. */
140 print_known_names ();
144 /* If we have to ignore errors make sure we use the appropriate name for
145 the to-character-set. */
146 orig_to_code
= to_code
;
149 const char *errhand
= strchrnul (to_code
, '/');
157 errhand
= strchrnul (errhand
, '/');
166 newp
= (char *) alloca (errhand
- to_code
+ nslash
+ 6 + 1);
167 cp
= mempcpy (newp
, to_code
, errhand
- to_code
);
170 memcpy (cp
, "IGNORE", sizeof ("IGNORE"));
175 /* POSIX 1003.2b introduces a silly thing: the arguments to -t anf -f
176 can be file names of charmaps. In this case iconv will have to read
177 those charmaps and use them to do the conversion. But there are
178 holes in the specification. There is nothing said that if -f is a
179 charmap filename that -t must be, too. And vice versa. There is
180 also no word about the symbolic names used. What if they don't
182 if (strchr (from_code
, '/') != NULL
)
183 /* The from-name might be a charmap file name. Try reading the
185 from_charmap
= charmap_read (from_code
, /*0, 1*/1, 0, 0);
187 if (strchr (orig_to_code
, '/') != NULL
)
188 /* The to-name might be a charmap file name. Try reading the
190 to_charmap
= charmap_read (orig_to_code
, /*0, 1,*/1,0, 0);
193 /* Determine output file. */
194 if (output_file
!= NULL
&& strcmp (output_file
, "-") != 0)
196 output
= fopen (output_file
, "w");
198 error (EXIT_FAILURE
, errno
, _("cannot open output file"));
203 /* At this point we have to handle two cases. The first one is
204 where a charmap is used for the from- or to-charset, or both. We
205 handle this special since it is very different from the sane way of
206 doing things. The other case allows converting using the iconv()
208 if (from_charmap
!= NULL
|| to_charmap
!= NULL
)
209 /* Construct the conversion table and do the conversion. */
210 status
= charmap_conversion (from_code
, from_charmap
, to_code
, to_charmap
,
211 argc
, remaining
, argv
, output
);
214 /* Let's see whether we have these coded character sets. */
215 cd
= iconv_open (to_code
, from_code
);
216 if (cd
== (iconv_t
) -1)
219 error (EXIT_FAILURE
, 0,
220 _("conversion from `%s' to `%s' not supported"),
221 from_code
[0] ? from_code
: nl_langinfo (CODESET
),
222 orig_to_code
[0] ? orig_to_code
: nl_langinfo (CODESET
));
224 error (EXIT_FAILURE
, errno
,
225 _("failed to start conversion processing"));
228 /* Now process the remaining files. Write them to stdout or the file
229 specified with the `-o' parameter. If we have no file given as
230 the parameter process all from stdin. */
231 if (remaining
== argc
)
233 if (process_file (cd
, stdin
, output
) != 0)
234 status
= EXIT_FAILURE
;
239 #ifdef _POSIX_MAPPED_FILES
246 printf ("%s:\n", argv
[remaining
]);
247 if (strcmp (argv
[remaining
], "-") == 0)
251 fd
= open (argv
[remaining
], O_RDONLY
);
255 error (0, errno
, _("cannot open input file `%s'"),
257 status
= EXIT_FAILURE
;
262 #ifdef _POSIX_MAPPED_FILES
263 /* We have possibilities for reading the input file. First try
264 to mmap() it since this will provide the fastest solution. */
265 if (fstat (fd
, &st
) == 0
266 && ((addr
= mmap (NULL
, st
.st_size
, PROT_READ
, MAP_PRIVATE
,
267 fd
, 0)) != MAP_FAILED
))
269 /* Yes, we can use mmap(). The descriptor is not needed
272 error (EXIT_FAILURE
, errno
,
273 _("error while closing input `%s'"),
276 if (process_block (cd
, addr
, st
.st_size
, output
) < 0)
278 /* Something went wrong. */
279 status
= EXIT_FAILURE
;
281 /* We don't need the input data anymore. */
282 munmap ((void *) addr
, st
.st_size
);
284 /* We cannot go on with producing output since it might
285 lead to problem because the last output might leave
286 the output stream in an undefined state. */
290 /* We don't need the input data anymore. */
291 munmap ((void *) addr
, st
.st_size
);
294 #endif /* _POSIX_MAPPED_FILES */
296 /* Read the file in pieces. */
297 if (process_fd (cd
, fd
, output
) != 0)
299 /* Something went wrong. */
300 status
= EXIT_FAILURE
;
302 /* We don't need the input file anymore. */
305 /* We cannot go on with producing output since it might
306 lead to problem because the last output might leave
307 the output stream in an undefined state. */
311 /* Now close the file. */
315 while (++remaining
< argc
);
318 /* Close the output file now. */
320 error (EXIT_FAILURE
, errno
, _("error while closing output file"));
326 /* Handle program arguments. */
328 parse_opt (int key
, char *arg
, struct argp_state
*state
)
342 /* Nothing, for now at least. We are not giving out any information
343 about missing character or so. */
346 /* Omit invalid characters from output. */
356 return ARGP_ERR_UNKNOWN
;
363 more_help (int key
, const char *text
, void *input
)
367 case ARGP_KEY_HELP_EXTRA
:
368 /* We print some extra information. */
369 return strdup (gettext ("\
370 Report bugs using the `glibcbug' script to <bugs@gnu.org>.\n"));
374 return (char *) text
;
378 /* Print the version information. */
380 print_version (FILE *stream
, struct argp_state
*state
)
382 fprintf (stream
, "iconv (GNU %s) %s\n", PACKAGE
, VERSION
);
383 fprintf (stream
, gettext ("\
384 Copyright (C) %s Free Software Foundation, Inc.\n\
385 This is free software; see the source for copying conditions. There is NO\n\
386 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
388 fprintf (stream
, gettext ("Written by %s.\n"), "Ulrich Drepper");
393 process_block (iconv_t cd
, char *addr
, size_t len
, FILE *output
)
395 #define OUTBUF_SIZE 32768
396 const char *start
= addr
;
397 char outbuf
[OUTBUF_SIZE
];
405 outlen
= OUTBUF_SIZE
;
406 n
= iconv (cd
, &addr
, &len
, &outptr
, &outlen
);
408 if (outptr
!= outbuf
)
410 /* We have something to write out. */
411 int errno_save
= errno
;
413 if (fwrite (outbuf
, 1, outptr
- outbuf
, output
)
414 < (size_t) (outptr
- outbuf
)
417 /* Error occurred while printing the result. */
419 conversion stopped due to problem in writing the output"));
426 if (n
!= (size_t) -1)
428 /* All the input test is processed. For state-dependent
429 character sets we have to flush the state now. */
431 outlen
= OUTBUF_SIZE
;
432 (void) iconv (cd
, NULL
, NULL
, &outptr
, &outlen
);
434 if (outptr
!= outbuf
)
436 /* We have something to write out. */
437 int errno_save
= errno
;
439 if (fwrite (outbuf
, 1, outptr
- outbuf
, output
)
440 < (size_t) (outptr
- outbuf
)
443 /* Error occurred while printing the result. */
445 conversion stopped due to problem in writing the output"));
457 /* iconv() ran into a problem. */
461 error (0, 0, _("illegal input sequence at position %ld"),
462 (long) (addr
- start
));
466 incomplete character or shift sequence at end of buffer"));
469 error (0, 0, _("internal error (illegal descriptor)"));
472 error (0, 0, _("unknown iconv() error %d"), errno
);
485 process_fd (iconv_t cd
, int fd
, FILE *output
)
487 /* we have a problem with reading from a desriptor since we must not
488 provide the iconv() function an incomplete character or shift
489 sequence at the end of the buffer. Since we have to deal with
490 arbitrary encodings we must read the whole text in a buffer and
491 process it in one step. */
492 static char *inbuf
= NULL
;
493 static size_t maxlen
= 0;
497 while (actlen
< maxlen
)
499 ssize_t n
= read (fd
, inptr
, maxlen
- actlen
);
502 /* No more text to read. */
507 /* Error while reading. */
508 error (0, errno
, _("error while reading the input"));
516 if (actlen
== maxlen
)
522 /* Increase the buffer. */
523 new_inbuf
= (char *) realloc (inbuf
, maxlen
+ 32768);
524 if (new_inbuf
== NULL
)
526 error (0, errno
, _("unable to allocate buffer for input"));
531 inptr
= inbuf
+ actlen
;
535 n
= read (fd
, inptr
, maxlen
- actlen
);
538 /* No more text to read. */
543 /* Error while reading. */
544 error (0, errno
, _("error while reading the input"));
551 while (actlen
< maxlen
);
554 /* Break again so we leave both loops. */
558 /* Now we have all the input in the buffer. Process it in one run. */
559 return process_block (cd
, inbuf
, actlen
, output
);
564 process_file (iconv_t cd
, FILE *input
, FILE *output
)
566 /* This should be safe since we use this function only for `stdin' and
567 we haven't read anything so far. */
568 return process_fd (cd
, fileno (input
), output
);
572 /* Print all known character sets/encodings. */
573 static void *printlist
;
574 static size_t column
;
575 static int not_first
;
578 insert_print_list (const void *nodep
, VISIT value
, int level
)
580 if (value
== leaf
|| value
== postorder
)
582 const struct gconv_alias
*s
= *(const struct gconv_alias
**) nodep
;
583 tsearch (s
->fromname
, &printlist
, (__compar_fn_t
) strverscmp
);
588 do_print_human (const void *nodep
, VISIT value
, int level
)
590 if (value
== leaf
|| value
== postorder
)
592 const char *s
= *(const char **) nodep
;
593 size_t len
= strlen (s
);
596 while (len
> 0 && s
[len
- 1] == '/')
599 for (cnt
= 0; cnt
< len
; ++cnt
)
600 if (isalnum (s
[cnt
]))
610 if (column
> 2 && column
+ len
> 77)
612 fputs ("\n ", stdout
);
624 fwrite (s
, len
, 1, stdout
);
630 do_print (const void *nodep
, VISIT value
, int level
)
632 if (value
== leaf
|| value
== postorder
)
634 const char *s
= *(const char **) nodep
;
642 add_known_names (struct gconv_module
*node
)
644 if (node
->left
!= NULL
)
645 add_known_names (node
->left
);
646 if (node
->right
!= NULL
)
647 add_known_names (node
->right
);
650 if (strcmp (node
->from_string
, "INTERNAL"))
651 tsearch (node
->from_string
, &printlist
,
652 (__compar_fn_t
) strverscmp
);
653 if (strcmp (node
->to_string
, "INTERNAL") != 0)
654 tsearch (node
->to_string
, &printlist
, (__compar_fn_t
) strverscmp
);
658 while (node
!= NULL
);
665 const struct gconvcache_header
*header
;
667 const struct hash_entry
*hashtab
;
670 header
= (const struct gconvcache_header
*) __gconv_get_cache ();
671 strtab
= (char *) header
+ header
->string_offset
;
672 hashtab
= (struct hash_entry
*) ((char *) header
+ header
->hash_offset
);
674 for (cnt
= 0; cnt
< header
->hash_size
; ++cnt
)
675 if (hashtab
[cnt
].string_offset
!= 0)
677 const char *str
= strtab
+ hashtab
[cnt
].string_offset
;
679 if (strcmp (str
, "INTERNAL") != 0)
680 tsearch (str
, &printlist
, (__compar_fn_t
) strverscmp
);
687 print_known_names (void)
692 /* We must initialize the internal databases first. */
693 h
= iconv_open ("L1", "L1");
696 /* See whether we have a cache. */
697 cache
= __gconv_get_cache ();
699 /* Yep, use only this information. */
703 struct gconv_module
*modules
;
705 /* No, then use the information read from the gconv-modules file.
706 First add the aliases. */
707 twalk (__gconv_get_alias_db (), insert_print_list
);
709 /* Add the from- and to-names from the known modules. */
710 modules
= __gconv_get_modules_db ();
712 add_known_names (modules
);
716 The following list contain all the coded character sets known. This does\n\
717 not necessarily mean that all combinations of these names can be used for\n\
718 the FROM and TO command line parameters. One coded character set can be\n\
719 listed with several different names (aliases).\n\n "), stdout
);
721 /* Now print the collected names. */
723 if (isatty (fileno (stdout
)))
725 twalk (printlist
, do_print_human
);
731 twalk (printlist
, do_print
);