为什么在读取 RAW 文件时会打印分段错误(核心转储)?

发布于 2025-01-13 13:11:38 字数 978 浏览 3 评论 0原文

你能告诉我为什么这个特定的代码会出现分段错误吗?我编写此代码是为了从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巷雨优美回忆 2025-01-20 13:11:38

在函数 findSize 中,您不应该关闭文件而应该倒回它:

// fclose(file);
rewind(file);

In the function findSize you shouldn't close the file but rewind it:

// fclose(file);
rewind(file);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文