c++ - 具有扩展字符 (128-255) 的 Linux 中的 open() 函数返回 -1 错误

标签 c++ c linux

当我尝试在 LINUX 中使用 open() 函数创建一个文件时,我得到一个错误 '-1',因为文件名包含扩展字符(例如:Björk.txt)。这里的文件包含一个特殊字符 ö (ASCII 148)

我正在使用下面的代码:

char* szUnixPath

/home/user188/Output/Björk.txt

open(szUnixPath, locStyle, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

我总是收到 -1 错误,并且没有创建文件。

当操作系统遇到 ASCII 148 时,它会抛出错误。

如果我使用代字号 ~(ASCII 126,示例:Bj~rk.txt)或任何其他低于 ASCII 值 128 的字符,同样的功能也能正常工作。

有人可以解释为什么我只对具有特殊字符范围在 128-255 之间的文件名得到 -1 错误吗?

最佳答案

我建议您自己尝试看看这个名称包含哪些字节。

在目录中创建文件,然后运行以下简单的 C 程序:

#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    /* Open directory */
    DIR * currdir = opendir(".");

    /* Iterate over files */
    struct dirent * directory_entry = NULL;
    while (NULL != (directory_entry = readdir(currdir)))
    {
        char * entry_name = directory_entry->d_name;
        printf("Directory entry: %s\n", entry_name);
        printf("Name bytes (len: %d):\n", strlen(entry_name));
        for (size_t i = 0; i < strlen(entry_name); ++i)
        {
            printf("\tname[%d] = %d\n", i, entry_name[i]);
        }
    }

    return 0;
}

我们可以很容易地在输出中看到“Björk”的长度是 6 个字节。我们可以看到这些字节值:

Directory entry: Björk
Name bytes (len: 6):
    name[0] = 66
    name[1] = 106
    name[2] = -61
    name[3] = -74
    name[4] = 114
    name[5] = 107

关于c++ - 具有扩展字符 (128-255) 的 Linux 中的 open() 函数返回 -1 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849332/

相关文章:

c++ - Qt 链接器错误 : "undefined reference to vtable"

c - autotools:一个项目有一个可执行文件、一个共享对象和一个 "shared"内部库

cublasStrsmBatched - 执行失败

linux - 如何使用 sed linux 将参数添加到行号

c++ - OpenSSL 添加可信系统证书

linux - 在 Debian Wheezy 上更新 libpq5 (>= 9.4~beta3)

C++从数据文件中读取行到某些变量

c++ - 比较两个字符串作为数值

c++ - OpenGL 绘图纹理

c - Linux二进制串行读取问题