Windows file conversion encoding

Кодировки в Windows

В данной статье пойдёт речь о кодировках в Windows. Все в жизни хоть раз использовали и писали консольные приложения как таковые. Нету разницы для какой причины. Будь-то выбивание процесса или же просто написать «Привет. Я не могу сделать кодировку нормальной, поэтому я смотрю эту статью!».

Тем, кто ещё не понимает, о чём проблема, то вот Вам:

А тут было написано:

Но никто ничего не понял.

В любом случае в Windows до 10 кодировка BAT и других языков, не использует кодировку поддерживающую Ваш язык, поэтому все русские символы будут писаться неправильно.

1. Настройка консоли в батнике

Сразу для тех, кто пишет chcp 1251 лучше написать это:

Первый способ устранения проблемы, это Notepad++. Для этого Вам нужно открыть Ваш батник таким способом:

Не бойтесь, у Вас откроется код Вашего батника, а затем Вам нужно будет сделать следующие действия:

Если Вам ничего не помогло, то преобразуйте в UTF-8 без BOM.

2. Написание консольных программ
Нередко люди пишут консольные программы(потому что на некоторых десктопные писать невозможно), а кодировка частая проблема.

Первый способ непосредственно Notepad++, но а если нужно сначала одну кодировку, а потом другую?

Сразу для использующих chcp 1251 пишите это:

Второй способ это написать десктопную программу, или же использовать Visual Studio. Если же не помогает, то есть первое: изменение кодировки вывода(Пример на C++).

Если же не сработает:

3. Изменение chcp 1251
Если же у Вас батник, то напишите в начало:

Теперь у Нас будет нормальный вывод в консоль. На других языках (С++):

4. Сделать жизнь мёдом
При использовании данного способа Вы не сможете:

  • Разрабатывать приложения на Windows ниже 10
  • Спасти мир от данной проблемы
  • Думать о других людях
  • Разрабатывать десктопные приложения, так как Вам жизнь покажется мёдом
  • Сменить Windows на версию ниже 10
  • Ну и понимать людей, у которых Windows ниже 10

Установить Windows 10. Там кодировка консоли специально подходит для языка страны, и Вам больше не нужно будет беспокоиться об этой проблеме. Но у Вас появится ещё 6 проблем, и вернуться к предыдущей лицензионной версии Windows Вы не сможете.

Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.

Практическое руководство. Сохранение и открытие файлов с использованием определенной кодировки How to: Save and open files with encoding

Вы можете сохранять файлы с определенной кодировкой для поддержки языков с двунаправленным письмом. You can save files with specific character encoding to support bidirectional languages. Можно также указать кодировку при открытии файла, чтобы система Visual Studio отобразила его правильно. You can also specify an encoding when opening a file, so that Visual Studio displays the file correctly.

Сохранение файла с кодировкой To save a file with encoding

В меню Файл выберите Сохранить файл как и затем нажмите кнопку раскрывающегося списка рядом с кнопкой Сохранить. From the File menu, choose Save File As, and then click the drop-down button next to the Save button.

Откроется диалоговое окно Дополнительные параметры сохранения. The Advanced Save Options dialog box is displayed.

Читайте также:  Git windows install github

В разделе Кодировка выберите нужную кодировку для файла. Under Encoding, select the encoding to use for the file.

При необходимости в разделе Завершение строк выберите формат для знаков конца строки. Optionally, under Line endings, select the format for end-of-line characters.

Этот параметр полезен, если предполагается обмениваться файлами с пользователями, работающими в другой операционной системе. This option is useful if you intend to exchange the file with users of a different operating system.

Если вы хотите работать с файлом, имеющим определенную кодировку, можно сообщить Visual Studio использовать эту кодировку при открытии файла. If you want to work with a file that you know is encoded in a specific way, you can tell Visual Studio to use that encoding when opening the file. Конкретный метод зависит от того, является ли файл частью проекта. The method you use depends on whether the file is part of your project.

Чтобы сохранить файл проекта с кодировкой, необходимо выгрузить проект. Только после этого станет доступна команда Сохранить файл как. If you want to save the project file with encoding, the Save File As option is not enabled until you unload the project.

Открытие файла с кодировкой, являющегося частью проекта To open an encoded file that is part of a project

В обозревателе решений щелкните файл правой кнопкой мыши и выберите команду Открыть с помощью. In Solution Explorer, right-click the file and choose Open With.

В диалоговом окне Открыть с помощью выберите редактор для открытия файла. In the Open With dialog box, choose the editor to open the file with.

Многие редакторы Visual Studio, такие как редактор форм, автоматически определяют кодировку и открывают файл соответствующим образом. Many Visual Studio editors, such as the forms editor, will auto-detect the encoding and open the file appropriately. Если вы воспользовались редактором, который позволяет указать кодировку, появляется диалоговое окно Кодировка. If you choose an editor that allows you to choose an encoding, the Encoding dialog box is displayed.

В диалоговом окне Кодировка выберите кодировку, которую должен использовать редактор. In the Encoding dialog box, select the encoding that the editor should use.

Открытие файла с кодировкой, не являющегося частью проекта To open an encoded file that is not part of a project

В меню Файл наведите указатель мыши на пункт Открыть, выберите элемент Файл или Файл из Интернета, а затем выберите нужный файл. On the File menu, point to Open, choose File or File From Web, and then select the file to open.

Нажмите кнопку раскрывающегося списка рядом с кнопкой Открыть и выберите пункт Открыть с помощью. Click the drop-down button next to the Open button and choose Open With.

Выполните шаги 2 и 3 из предыдущей процедуры. Follow Steps 2 and 3 from the preceding procedure.

How to set file encoding format to UTF8 in C++

A requirement for my software is that the encoding of a file which contains exported data shall be UTF8. But when I write the data to the file the encoding is always ANSI. (I use Notepad++ to check this.)

What I’m currently doing is trying to convert the file manually by reading it, converting it to UTF8 and writing the text to a new file.

line is a std::string
inputFile is an std::ifstream
pOutputFile is a FILE*

Unfortunately the encoding is still ANSI. I searched a while for a solution but I always encounter the solution via MultiByteToWideChar and WideCharToMultiByte. However, this doesn’t seem to work. What am I missing here?

I also looked here on SO for a solution but most UTF8 questions deal with C# and php stuff.

4 Answers 4

On Windows in VC++2010 it is possible (not yet implemented in GCC, as far as i know) using localization facet std::codecvt_utf8_utf16 (i.e. in C++11). The sample code from cppreference.com has all basic information you would need to read/write UTF-8 file.

Читайте также:  Mac os как открыть файловую систему

It sets the ANSI encoded file to UTF-8 (checked in Notepad). Hope this is what you need.

On Windows, files don’t have encodings. Each application will assume an encoding based on its own rules. The best you can do is put a byte-order mark at the front of the file and hope it’s recognized.

AFAIK, fprintf() does character conversions, so there is no guarantee that passing UTF-8 encoded data to it will actually write the UTF-8 to the file. Since you already converted the data yourself, use fwrite() instead so you are writing the UTF-8 data as-is, eg:

The type char has no clue of any encoding, all it can do is store 8 bits. Therefore any text file is just a sequence of bytes and the user must guess the underlying encoding. A file starting with a BOM indicates UTF 8, but using a BOM is not recommended any more. The type wchar_t in contrast is in Windows always interpreted as UTF 16.

So let’s say you have a file encoded in UTF 8 with just one line: «Confucius says: Smile. 孔子说:微笑!😊.» The following code snippet appends this text once more, then reads the first line and displays it in a MessageBoxW and MessageBoxA . Note that MessageBoxW shows the correct text while MessageBoxA shows some junk because it assumes my local codepage 1252 for the char* string.

Note that I have used the handy CA2W class instead of MultiByteToWideChar . Be careful, the CP_Whatever argument is optional and if omitted the local codepage is used.

Windows file conversion encoding

Text Encoding Converter

Text Encoding Converter converts text files encoding from one to another, mainly ks_c_5601-1987 to UTF-8 .

There is no need for installation. Instead, download one of the following options:

Once unzip the file, it works with its default settings. However, if you want to change some settings, you should look after the Aliencube.TextEncodingConverter.exe.config file.

  • encoding.input : Input encoding format. Default value is ks_c_5601-1987 .
  • encoding.output : Output encoding format. Default value is utf-8 .
  • converter.extensions : Comma delimited extensions to convert. As a default, the application only consider .csv and .txt files.
  • converter.backup : Value that specifies whether to backup the original files or not. Default value is true .
  • converter.backupPath : Relative or absolute path for backup. Default value is Backup . If converter.backup is set to false , this will be ignored.
  • converter.outputPath : Relative or absolute path for output. Default value is Output .

Text Encoding Converter console application requires the following parameters:

  • /d | /f : Indicates whether the input is directory or file.
  • /ie:xxxx : specifies the input file encoding. It can be either codepage or IANA name defined here. Double quote might be necessary for input directory/file path.
  • /oe:xxxx : specifies the output file encoding. It can be either codepage or IANA name defined here. Double quote might be necessary for output directory/file path.
  • /i:xxxx : specifies the input path. It can be either directory or file.
  • /o:xxxx : specifies the output directory path.

Here is a sample command:

Windows GUI Application

Text Encoding Converter Windows GUI application is intuitive to use:

  • Choose input encoding option: ks_c_5601-1987 is initially set as a default.
  • Choose output encoding option: utf-8 is initially set as a default.
  • Select files to convert: Click the Browse button to select files.
  • Convert: Click the Convert button to convert.
  • Console Application for Mac
  • GUI Application for Mac

Your contributions are always welcome! All your work should be done in your forked repository. Once you finish your work, please send us a pull request onto our dev branch for review.

Text Encoding Converter is released under MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Читайте также:  Tl wn725n ������� ��� mac os

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

This converts text files encoding from one to another, mainly ks_c_5601-1987 to UTF-8.

What encoding are filenames in NTFS stored as?

I’m just getting started on some programming to handle filenames with non-english names on a WinXP system. I’ve done some recommended reading on unicode and I think I get the basic idea, but some parts are still not very clear to me.

Specifically, what encoding (UTF-8, UTF-16LE/BE) are the file names (not the content, but the actual name of the file) stored in NTFS? Is it possible to open any file using fopen(), which takes a char*, or do I have no choice but to use wfopen(), which uses a wchar_t*, and presumably takes a UTF-16 string?

I tried manually feeding in a UTF-8 encoded string to fopen(), eg.

but this came out as ‘ê°€.txt’.

I was under the impression (which may be wrong) that a UTF8-encoded string would suffice in opening any filename under Windows, because I seem to vaguely remember some Windows application passing around (char*), not (wchar_t*), and having no problems.

Can anyone shed some light on this?

3 Answers 3

NTFS stores filenames in UTF-16, however fopen is using ANSI (not UTF-8).

In order to use an UTF16-encoded file name you will need to use the Unicode versions of the file open calls. Do this by defining UNICODE and _UNICODE in your project. Then use the CreateFile call or the wfopen call.

fopen() — in MSVC on windows does not (by default) take a utf-8 encoded char*.

Unfortunately utf-8 was invented rather recently in the great scheme of things. Windows APIs are divided into Unicode and Ansi versions. every windows api that takes or deals with strings is actually available with a W or A suffix — W for «Wide» character/Unicode and A for Ansi. Macro magic hides all this away from the developer so you just call CreateFile with either a char* or a wchar_t* depending on your build configuration without knowing the difference.

The ‘Ansi’ encoding is actually not a specific encoding:- But means that the encoding used for «char» strings is specific to the locale setting of the PC.

Now, because c-runtime functions — like fopen — need to work by default without developer knowledge — on windows systems they expect to receive their strings in the windows local encoding. msdn indicates the microsoft c-runtime api setlocal can change the locale of the current thread — but specifically says that it will fail for any locales that need more than 2 bytes per character — like utf-8.

So, on Windows there is no shortcut. You need to use wfopen, or the native API CreateFileW (or create your project using the Unicode build settings and just call Createfile) with wchar_t* strings.

Оцените статью