【发布时间】:2017-03-15 21:46:35
【问题描述】:
我读取了一个文件并存储了所有这样的字符:
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");
}
}
问题是,如果我阅读每个字符,我已经获得了文件的内容,但如果我这样做了:
printf("content: %s",content);
我只得到一个符号而不是文本,而我需要在 json 回复的参数中传递带有正确文本的内容变量。
这是文件的第一行(CRC32):
�ex.txt k��X�?xml version="1.0" encoding="utf-8"?
【问题讨论】:
-
它可能不会解决问题,但使用
fread()而不是一次读取一个字符。sizeof(char)始终为 1,这是强制性的。 -
我用过 fread 但同样的问题
-
我认为你的问题是输入文件。因为这段代码很好。
-
该文件不是一个简单的txt文件,它看起来像xml语法但开头有一个CRC32,我添加一个例子
-
问题不在于读数,而在于您输出它们的方式。一种可能是检查每个字节值并用“。”打印它们。当它们不可打印时。这有点类似于 hexdump -C 会做的事情。
man ascii可以为您提供一个起点,但请记住,像 unicode 这样的东西会使“可打印”检测变得相当复杂。
标签: c arrays json char readfile