c++ - fgetws 无法从 FILE* 中获取准确的宽字符字符串

标签 c++ file-io wstring widechar

我正在使用 fgetws 从文件中逐行获取一些字符串。我拥有的文件来自 popen 命令。这是代码片段:

    FILE* pInstalledApps = popen( command.c_str(), "r" );
    if( NULL != pInstalledApps )
    {
        wchar_t currentAppPath [kMaximumAppPathLength];

        // Reading app paths one line at a time.
        while ( ! feof (pInstalledApps) )
        {
            if ( fgetws  ( currentAppPath, kMaximumAppPathLength, pInstalledApps) == NULL )
            {
                break;
            }
            wchar_t *pCharPos = NULL;
            if ( ( pCharPos = wcschr( currentAppPath, L'\n' ) ) != NULL )
            {
                *pCharPos = L'\0';
            }
            std::wstring appPath( currentAppPath );

                            //Do something with the wstring
        }
        pclose( pInstalledApps );
    }

当我获取的字符串 currentAppPath 具有宽字符字符串时,我获取的 appPath 没有预期的字符串。例如,如果我从 FILE 中获取的字符串是 10teciêêênks,我的 appPath 变量将具有 10tecieÌeÌnks

最佳答案

这看起来像是编码(或更具体地说,解码)问题。宽字符 API 函数不会自动检测数据的字符编码。您需要在应用程序中设置它,例如:

#include <locale.h>

setlocale(LC_ALL, "en.UTF-8");

fgetws 的手册页指出:

The behavior of fgetws() depends on the LC_CTYPE category of the current locale.

所以使用:

setlocale(LC_CTYPE, "en.UTF-8");

应该也可以。

注意:以上假定数据是 UTF-8 编码的。

更新:可以通过执行以下操作来保留当前语言环境:

char *prev_locale = strdup(setlocale(LC_CTYPE, NULL));
setlocale(LC_CTYPE, "en.UTF-8");
// ...
setlocale(LC_CTYPE, prev_locale);
free(prev_locale);

关于c++ - fgetws 无法从 FILE* 中获取准确的宽字符字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23936105/

相关文章:

c++ - Linux 中的实时 RX 和 TX 速率

c++ - 是否有免费软件实用程序可以监视 C++ 应用程序的内存泄漏?

c++ - 在 Linux 中是否有将 wstring 或 wchar_t* 转换为 UTF-8 的内置函数?

c++ - ffmpeg C++ 和 AVFormatContext

java - 在 Java 中读取文件、替换单词并写入新文件

c++ - 对 fstream 输出操作执行 'catch all' 错误检查的正确方法是什么?

C++ 基本文件 i/o,读取失败

c++ - 在 C++ 中将整数更改为 wstring

c++ - 访问存储在 vector 中的指针内的字符串时崩溃

c++ - 返回其自身类型的结构的结构属性