C 文件读取产生意外错误

标签 c file printf

我正在回到 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/

相关文章:

c - 从字符串中打印出某个单词

c - 如何设置 if 以检查 C 中的多个值?

C语言,如何修复段错误

c - 使用 Printf 打印二维数组元素

c - 将 Rust 变量传递给期望能够修改它的 C 函数

c++ - 转换 C 数组文字以在 C++ 构造函数中工作?

java - 属性文件在 Java 中返回为 null

java - 文件未找到异常,相同目录存在

C printf 浮点四舍五入

C Sprintf 格式错误