[英]Printing random characters when reading file
I have a config.txt file that looks like this:我有一个如下所示的 config.txt 文件:
2
2
[3, 8]
[4, 2]-[12, 7]
[1, 10]-[12, 1]
And I am trying to read its content to process later.我正在尝试阅读其内容以供稍后处理。 However, when I was trying my program and printing the file content it ouputs more characters than are in the file, even when I terminate the string myself.但是,当我尝试我的程序并打印文件内容时,它输出的字符多于文件中的字符,即使我自己终止了字符串也是如此。 It's like the length of the file is overestimated by the program.这就像程序高估了文件的长度。 This is the output of the printf:这是 printf 的输出:
2
2
[3, 8]
[4, 2]-[12, 7]
[1, 10]-[12, 1]df
Obviously the two characters df should not be there.显然这两个字符df不应该在那里。 What am I doing wrong.我究竟做错了什么。 I googled around but I can't find a clear answer.我用谷歌搜索,但找不到明确的答案。 This is my C program:这是我的 C 程序:
#include <stdio.h>
#include <stdlib.h>
void readFile(const char *fileName, char *text);
void readFile(const char *fileName, char *text)
{
FILE *f;
long length;
f = fopen(fileName, "r");
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
text = malloc(length + 1);
if(text)
{
fread (text, 1, length, f);
}
fclose (f);
text[length] = '\0';
printf(text);
}
int main(void)
{
char *fileText;
readFile("config.txt", fileText);
return 1;
}
就像user3121023已经建议的那样,在 fopen 语句中将“r”更改为“rb”解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.