'Why does this print a segmentation fault (core dumped) while reading a RAW file?
Can you tell me why does this particular code gives a segmentation fault? I had written this to read data from a RAW file and to put it in a buffer array. The RAW file has blocks of 512 bytes each so the array is 512 in size.
#include <stdio.h>
#include <stdlib.h>
long int findSize(FILE *file);
int buffer[512];
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover IMAGE\n");
}
FILE *file = fopen(argv[1], "r");
long int size = findSize(file);
int blocks = size/512;
int counts = 0;
for (int i = 0; i < blocks; i++)
{
while (fread(buffer, 1, 512, file) == 512)
{
printf("%i\n", buffer[counts]);
counts++;
}
}
}
long int findSize(FILE *file)
{
// checking if the file exist or not
if (file == NULL) {
printf("File Not Found!\n");
return -1;
}
fseek(file, 0L, SEEK_END);
// calculating the size of the file
long int res = ftell(file);
// closing the file
fclose(file);
return res;
}
Solution 1:[1]
In the function findSize you shouldn't close the file but rewind it:
// fclose(file);
rewind(file);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | August Karlstrom |
