问题
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;
}
回答1:
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);
回答2:
char * file_content is just a pointer, you need to allocate memory to store the string.
char * file_content;
file_content = malloc(fsize);
回答3:
"..but I get a segment fault"
Obviously because you're attempting to write to an uninitialized file_content
Allocated memory for file_content before use
char * file_content =malloc(fsize);
来源:https://stackoverflow.com/questions/18701924/get-a-segment-fault-while-reading-a-file