I want to open a file, read its content and store it in an array using C code.
I did it on my Windows laptop and it works but when i try the code on my Raspberrypi i get segmentation faults. I've been trying for a while to debugm I'm quite new to C so I'm having trouble finding what I did wrong.
char *readFile(char *fileName)
{
FILE *ptr_file;
char *ptr_data;
int n = 0;
char c;
ptr_file = fopen(fileName, "r");
if(ptr_file == NULL)
{
perror("File could not be opened.\n");
exit(EXIT_FAILURE);
}
fseek(ptr_file, 0, SEEK_END);
long f_size = ftell(ptr_file);
fseek(ptr_file,0, SEEK_SET);
ptr_data = (char *)malloc(f_size+1);
if(ptr_data == NULL)
{
perror("MALLOC FAILED");
exit(EXIT_FAILURE);
}
while((c = fgetc(ptr_file)) != EOF)
{
ptr_data[n++] = (char)c;
}
ptr_data[n] = '\0';
fclose(ptr_file);
return ptr_data;
}
to me it seems like the segmentations fault appears in the while loop after the call to malloc
.
Why does it work on my laptop and not on the raspberrypi?
at the same time i dont understand why i get segmentation faults on my RPi if id do this:
int main(int argc, char *argv[])
{
char data[100] = {};
FILE *ptr_file;
char *ptr_data=data;
int n = 0, i = 0;
char c;
ptr_file = fopen(fileName, "r");
if(ptr_file == NULL)
{
perror("File could not be opened.\n");
exit(EXIT_FAILURE);
}
while((c = fgetc(ptr_file)) != EOF)
{
ptr_data[n++] = (char)c;
}
ptr_data[n] = '\0';
while(i <n,i++)
{
printf("%c\n",data[i]);
fclose(ptr_file);
}
return 0; }