我回到C并从文件读入时遇到错误。当我正在读取的文件长于1行时,下面的代码字很好,但是当其一行文本时,它会生成带有'> ??'的第二行 人物。只是想知道我在这里可能做错了什么。
我已经包含了代码,读取的text.txt文件和示例输出。
提前为任何帮助加油。
text.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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句