Answer the question
In order to leave comments, you need to log in
Why is a file no longer available for opening (fopen) after a multiple number of write cycles?
Hello. The task is to open the image file of the fat32 flash drive and read / write data to / from it. Data is read or written in blocks of 512 * n bytes. There can be no guaranteed way out of the file (in fact, access to the hardware flash drive that fatfs works with is simulated).
Available:
Operating system: Ubuntu 18.04.3 LTS, x64
File (256 MB fat32 micro-sd image) created by the following command sequence:
$ sudo dd if=/dev/zero of=microsd.img bs=512 count=524288
$ sudo mkfs.fat -F32 -v -I microsd.img
$ sudo chmod 777 microsd.img
$ sudo chown user_name:user_name microsd.img
-m32 -O0 -g3 -fdata-sections -ffunction-sections -Wl,--gc-sections -std=gnu99
// Путь до файла верный, работа ведется только с 1 файлом.
const char FILE_MICROSD_PATH[] = "../resurse/microsd.img";
// Размер блока стандартные 512 байт.
#define SD_BLOCK_SIZE 512
static FILE *sd = NULL;
int sdio_write (const uint32_t *buf, uint32_t block_num, uint32_t num_block) {
if ((sd = fopen(FILE_MICROSD_PATH, "r+b")) == NULL) {
return -1;
};
if (fseek(sd, block_num*SD_BLOCK_SIZE, SEEK_SET) != 0) {
fclose(sd);
sd = NULL;
return -1;
}
if (fwrite(buf, SD_BLOCK_SIZE, num_block, sd) != num_block) {
fclose(sd);
sd = NULL;
return -1;
};
int rv = fclose(sd);
sd = NULL;
return rv;
}
int sdio_read (uint32_t *buf, uint32_t block_num, uint32_t num_block) {
if ((sd = fopen(FILE_MICROSD_PATH, "r+b")) == NULL) {
return -1;
};
if (fseek(sd, block_num*SD_BLOCK_SIZE, SEEK_SET) != 0) {
fclose(sd);
sd = NULL;
return -1;
}
if (fread(buf, SD_BLOCK_SIZE, num_block, sd) != num_block) {
fclose(sd);
sd = NULL;
return -1;
};
int rv = fclose(sd);
sd = NULL;
return rv;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question