我正在回到 C 中,但在从文件中读取时遇到了错误。当我正在阅读的文件长于 1 行时,下面的代码字很好,但是当它的一行文本产生第二行时,它会产生“>??”人物。只是想知道我在这里可能做错了什么。
我已经包含了代码、text.txt 及其读数和示例输出。
提前为任何帮助干杯。
文本.txt "你好这是一个句子"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char * argv[]) {
FILE * fp;
char * buff;
int i = 0;
fp = fopen("text.txt", "a+");
if(fp == NULL)
{
perror("exiting\n");
exit(EXIT_FAILURE);
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
//The file read keeps adding ?? to the 2nd line of the file. I've tried the two pieces of code below
//buff = malloc(size);
buff = (char*) malloc(sizeof(char)*size);
fread(buff, 1, size, fp);
printf("%s\n\n", buff);
fclose(fp);
return 0;
}
样本输出
[H[2Jbash-3.2$ ./a.out
你好这是一个句子 v>äˇ
bash-3.2$ q[退出 退出
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char * argv[]) {
FILE * fp;
char * buff;
int i = 0;
fp = fopen("text.txt", "a+");
if(fp == NULL)
{
perror("exiting\n");
exit(EXIT_FAILURE);
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
// lowtech: this is the fix of you problem
buff = (char*) malloc(sizeof(char)*size + 1);
memset(buff, '\0', sizeof(char)*size + 1);
fread(buff, 1, size, fp);
printf("%s\n\n", buff);
fclose(fp);
return 0;
}
关于C 文件读取产生意外错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26555971/