gpt4 book ai didi

c - strlen() 返回一个包含 null 终止符的值

转载 作者:行者123 更新时间:2023-12-02 18:12:33 24 4
gpt4 key购买 nike

我正在使用使用 Clang 进行编译的 Ubuntu 机器。

我正在读取一个简单的文件,将其存储到缓冲区中,然后获取长度。我预计会得到 5 分,但得到了 6 分。

strlen() 不应包含空终止符。这可能是因为我对缓冲区执行了强制转换吗?

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main() {

unsigned char buffer[30];
memset(buffer, '\0', 30);

int fd_read = open("test.txt", O_RDONLY);
read(fd_read, buffer, 29);

ssize_t length = strlen((const char *)buffer);
printf("%zu\n", length);
}

test.txt的内容:

Hello

输出:

6

最佳答案

strlen() isn't suppose to include the null terminator.

确实如此。

Is this perhaps because I performed a cast on the buffer?

强制转换是不必要的,但这并不是导致问题的原因。

I'm reading a simple file, storing it into a buffer then getting the length. I'm anticipating receiving a 5 but got a 6.

可能的情况是,正如 Chris Dodd 所指出的,在读取的字符串末尾有换行符,其中 strlen 会计数。删除它:

buffer[strcspn(buffer, "\n")] = '\0';

有关代码的其他注意事项:

  • 您应该验证open的返回值以确认文件已成功访问。

  • memset(buffer, '\0', 30); 是不必要的,您可以 null 终止buffer:

    ssize_t nbytes = read(fd_read, buffer, sizeof buffer - 1);

    if(nbytes >= 0)
    buffer[nbytes] = '\0';

    或者你可以用 0 初始化数组:

    unsigned char buffer[30] = {'\0'}; // or 0

关于c - strlen() 返回一个包含 null 终止符的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72072285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com