gpt4 book ai didi

Char* 从 char 数组中解析错误

转载 作者:行者123 更新时间:2023-11-30 18:15:47 25 4
gpt4 key购买 nike

我读取一个文件并存储所有字符,如下所示:

void ReadFile()
{
int c;
FILE *file;

int string_size;
file = fopen("/userFiles/ex.txt", "r");
char * content;
if (file)
{

// Seek the last byte of the file
fseek(file, 0, SEEK_END);
// Offset from the first to the last byte, or in other words, filesize
string_size = ftell(file);
// go back to the start of the file
rewind(file);
// Allocate a string that can hold it all
content = malloc((string_size + 1) * sizeof(char));

int i = 0;

while ((c = getc(file)) != EOF)
{
//printf("%c",(char) c);
content[i] = (char) c;
i++;
}

content[string_size] = '\0';
printf("content: %s",content);
fclose(file);

}
else
{
printf("not load\n");
}

}

问题是,如果我读取每个 carachter,我就得到了文件的内容,但如果我这样做了:

printf("content: %s",content);

我只有一个符号而不是文本,而我需要在 json 回复的参数中传递带有正确文本的内容变量。

这是文件的第一行(CRC32):

�ex.txt k��X� ?xml version="1.0" encoding="utf-8"?

最佳答案

我编译并运行了以下代码,执行时没有显示出重大问题。

我使用的可编译版本是(cmdline:gcc main.c -Wall -Wextra -o main):

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

int main(void)
{
int c;
FILE *file;

int string_size;
file = fopen("plop", "r");
char * content;
if (file == NULL)
{
perror("fprintf");
return 1;
}

// Seek the last byte of the file
fseek(file, 0, SEEK_END);
// Offset from the first to the last byte, or in other words, filesize
string_size = ftell(file);
// go back to the start of the file
rewind(file);
// Allocate a string that can hold it all
content = malloc((string_size + 1) * sizeof(char));

int i = 0;

while ((c = getc(file)) != EOF)
{
//printf("%c",(char) c);
content[i] = (char) c;
i++;
}

content[string_size] = '\0';

printf("content: %s", content);

return 0;
}

也许您的文件有二进制内容?
您提到的打印符号是什么?

关于Char* 从 char 数组中解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811141/

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