2

I have an assignment that do FAT12 system. Follow the requirement, I need 2 functions to read sector and multi sector. Those functions in HAL layer. I just tested in app (main) layer below: In HAL.c:

#define SIZE_OF_SECTOR  512
static FILE* s_pimage = NULL;

void kmc_open_img_file()
{
    s_pimage = fopen("floppy.img", "rb");
    if(NULL == s_pimage)
    {
        printf("Can not open file!");
    }
}

int32_t kmc_read_sector(uint32_t index, uint8_t *buff)
{
    uint32_t offset = 0;
    int32_t num_of_bytes = 0;

    offset = SIZE_OF_SECTOR * index;
    fseek(s_pimage, SIZE_OF_SECTOR * index, SEEK_SET);
    num_of_bytes = (int32_t)fread(buff, 1, SIZE_OF_SECTOR, s_pimage);
   
    if (num_of_bytes == 0) printf("Fail");
    return num_of_bytes;
}

and in main: (added header file)

int main()
{
    kmc_open_img_file();

    uint8_t *buff = NULL ;
    int32_t a = kmc_read_sector(0, buff);

    printf("%d", a);

    kmc_close_img_file();
    return 0;
}

Result :Fail and 0 byte.

Can anyone help me solve it without extern variable? (this is requirement too)

  • Why would you need an extern variable? You just need to call the functions. But you need to provide a valid buffer for reading the sector. `buff` just contains a `NULL` pointer and does not point to memory you are allowed to write data to. Use `malloc` or make it an array instead. – Gerhardh Dec 01 '21 at 08:02
  • Is there any reason why you use data types different from the types defined by function spec? `fread` returns `size_t`. `fseek` takes a `long`. Are you suffering from MISRA checker complaining about using generic type? ;) – Gerhardh Dec 01 '21 at 08:06
  • @Gerhardh yesss, use generic type is fine as well but I must use stdint library for my assignment – Nguyễn Phùng Thái Cường Dec 01 '21 at 08:13
  • Well, you may (and should) use these types for your own functions. For functions that someone else defined, you should stick to the types used there. What happens if the types do not match? – Gerhardh Dec 01 '21 at 08:15
  • @Gerhardh Warning may occur, casting is dangerous. But if it did not lose data or something else, i think it would be acceptant – Nguyễn Phùng Thái Cường Dec 01 '21 at 08:22
  • 1
    Assuming that by "external variable" you mean `s_pimage`: Let `kmc_open_img_file()` return the file pointer, and pass it as an argument to `kmc_read_sector()`. The details are left as an exercise to you. – the busybee Dec 01 '21 at 09:28

0 Answers0