读取文件时出现段错误 [英] Get a segment fault while reading a file
本文介绍了读取文件时出现段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想读取整个文件内容并打印出来,但是出现段错误,我找不到代码有什么问题...
I want to read the whole file content and print it out , but I get a segment fault , I can't find what's wrong with the code ...
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
long fsize;
file = fopen("./input.txt","r");
if(file != NULL){
//get file size
fseek(file,0,SEEK_END);
fsize = ftell(file);
rewind(file);
// print
char * file_content;
fgets(file_content,fsize,file);
puts(file_content);
}
else{
printf("open failure\n");
}
fclose(file);
return 0;
}
推荐答案
您传递给fgets
(file_content
)的指针未初始化.它应该指向一个足够大的内存块,以包含指定数量的字节(fsize
).您可以使用malloc
分配内存.
The pointer you pass to fgets
(file_content
) is uninitialized. It should be pointing to a block of memory large enough to contain the specified number (fsize
) of bytes. You can use malloc
to allocate the memory.
char* file_content = (char*)malloc(fsize);
这篇关于读取文件时出现段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文