在c上打印char的意外行为

发布于 2025-02-06 21:55:40 字数 784 浏览 2 评论 0原文

我得到当我尝试在文件中打印字符串时,这些意外的chars。我该如何处理这种情况?

这是我的代码:

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

char *readFile(char *filename)
    {
        char * buffer;
        long length;
        FILE * f = fopen (filename, "r");
        if (f)
        {
            fseek (f, 0, SEEK_END);
            length = ftell (f);
            fseek (f, 0, SEEK_SET);
            buffer = malloc (length);
            if (buffer)
            {
                fread (buffer, 1, length, f);
            }
            fclose (f);
        }
        return buffer;
    }

int main() {

    char *firstS = readFile("file.txt");
    printf("%s \n", firstS);

    return 0;
}

I am getting these unexpected chars when I try to print the string inside of a file. How can I deal with this situation?

This is my code:

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

char *readFile(char *filename)
    {
        char * buffer;
        long length;
        FILE * f = fopen (filename, "r");
        if (f)
        {
            fseek (f, 0, SEEK_END);
            length = ftell (f);
            fseek (f, 0, SEEK_SET);
            buffer = malloc (length);
            if (buffer)
            {
                fread (buffer, 1, length, f);
            }
            fclose (f);
        }
        return buffer;
    }

int main() {

    char *firstS = readFile("file.txt");
    printf("%s \n", firstS);

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞎闹 2025-02-13 21:55:40

您不是nul终止字符串。取而代之的是,

buffer = malloc(length+1);

请执行此操作,然后在文件中读取 时

buffer[length] = '\0';

printf读取buffer 时, ,它会调用不确定的行为printf愉快地读取,直到找到一个'\ 0''。另请注意,您应该初始化buffer为null:

char * buffer = NULL;

并在打印之前在main中检查。如果打开文件有问题,则您将一个非初始化的buffer返回到main,然后尝试从中读取这是另一个UB调查器:

char *firstS = readFile("file.txt");
if (firstS != NULL)
{
    printf("%s \n", firstS);
}
else
{
    // print error message to your liking
}

You're not NUL terminating your string. Instead, do

buffer = malloc(length+1);

and then after you read in the file

buffer[length] = '\0';

When printf reads past the allocated memory for buffer, it invokes undefined behavior, printf happily reads along until it finds a '\0'. Also note you should initialize buffer to NULL:

char * buffer = NULL;

and check for that back in main before you print. If there's a problem opening the file for instance, you return an uninitialized buffer to main, and trying to read from that is another UB invoker:

char *firstS = readFile("file.txt");
if (firstS != NULL)
{
    printf("%s \n", firstS);
}
else
{
    // print error message to your liking
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文