为什么在读取 RAW 文件时会打印分段错误(核心转储)?
你能告诉我为什么这个特定的代码会出现分段错误吗?我编写此代码是为了从 RAW 文件中读取数据并将其放入缓冲区数组中。 RAW 文件具有每个 512 字节的块,因此数组的大小为 512。
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在函数 findSize 中,您不应该关闭文件而应该倒回它:
In the function findSize you shouldn't close the file but rewind it: