我有以下文字(D:/tst.txt):
blah
blah
blah
我写了以下程序:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// read file to text
char *path = "D:/tst.txt";
FILE *f = fopen(path, "r");
if(!f)
return EXIT_FAILURE;
fseek(f, 0, SEEK_END);
long size = ftell(f);
fseek(f, 0, SEEK_SET);
char *text = malloc((size + 1) * sizeof(char));
text[size] = '\0';
fread(text, sizeof(char), size, f);
fclose(f);
// Test result
printf("Size of text: %ld\n", size);
printf("Text:\n");
printf("%s", text);
}
输出:
Size of text: 16
Text:
blah
blah
blah══
大小是正确的,因为行结尾是&#34; \ r \ n&#34;。但是文字不包含&#39; \ r&#39;它包含2个垃圾符号。
我可以获得正确的文字吗?