从文件一次读取512个字节并检查内部是什么?

hao*_*ark 0 c

我有一个包含很多jpegs的大文件.所有jpegs都需要逐个提取.以下是我解决此问题的第一步:

1)定义"block"变量并为其分配512字节的存储空间

2)打开包含所有jpeg的文件并循环遍历eof

3)抓住第一个块(512字节),看看里面是什么

目前我的代码没有编译.这是我的错误:

 recover.c:27:19: error: implicitly declaring C library function
 'malloc' with type 'void *(unsigned int)' [-Werror]
     char* block = malloc(BYTE * 512);
                   ^ recover.c:27:19: note: please include the header <stdlib.h> or explicitly provide a declaration for 'malloc'
 recover.c:27:26: error: unexpected type name 'BYTE': expected
 expression
     char* block = malloc(BYTE * 512);
                          ^ recover.c:45:18: error: conversion specifies type 'int' but the argument has type 'char *'
 [-Werror,-Wformat]
         printf("%c", block);
                 ~^   ~~~~~
                 %s
Run Code Online (Sandbox Code Playgroud)

到目前为止这是我的代码:

#include <stdio.h>
#include <stdint.h>

typedef uint8_t BYTE;

//SOI - 0xFF 0xD8
//EOI - 0xFF 0xD9
//APPn - 0xFF 0xEn    
int main(void)
{
    //FAT - 512 bytes per block
    char* block = malloc(BYTE * 512);

    //open file containing pictures
    FILE* fh = fopen("card.raw", "rd");

    //make sure the file opened without errors
    if (fh == NULL)
    {
        printf("something went wrong and file could not be opened");
        return 1;
    }

    while (!feof(fh))
    {
        setbuf(fh, block);
        printf("%c", block);
    }

    fclose(fh);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?为什么不是char*block = malloc(BYTE*512); 分配512个字节,但抛出错误?另外,由于我甚至无法编译这篇文章,我是否正确读取了512个字节?如果没有,我该怎样才能完成这个?

谢谢.

Jor*_*eña 5

你想要:

#include <stdlib.h>
Run Code Online (Sandbox Code Playgroud)

得到的定义malloc().

char* block = malloc(BYTE * 512);
Run Code Online (Sandbox Code Playgroud)

应该是(因为malloc已经以字节为单位取得参数; sizeof(BYTE)将返回1):

char* block = malloc(512);
Run Code Online (Sandbox Code Playgroud)

和:

printf("%c", block);
Run Code Online (Sandbox Code Playgroud)

应该:

printf("%s", block);
Run Code Online (Sandbox Code Playgroud)

而像EJP在评论说,虽然这不是一个错误,没有用于动态分配的实际需要buffermalloc().您已经知道您将需要512字节,因此您可以用以下内容替换该行:

char block[512];
Run Code Online (Sandbox Code Playgroud)

我认为你使用clang作为你的编译器,正如你所看到的,它的错误消息非常有用,它基本上告诉你如何修复它.