The f_open function creates or opens the file and initialize a file object structure to be used to access the file.
FRESULT f_open ( FIL* FileObject, // Pointer to the file object structure const char* FileName, // Pointer to the file neme BYTE ModeFlags // Mode flags );
| Value | Description |
|---|---|
| FA_READ | Specifies read access to the object. Data can be read from the file. Combine with FA_WRITE for read-write access. |
| FA_WRITE | Specifies write access to the object. Data can be written to the file. Combine with FA_READ for read-write access. |
| FA_UNBUFFERED | This is for only FatFs module. When not specified, the file can be read/written in stream I/O via the file read/write buffer pointed by member 'buffer' in the file object. When specified, file read/write buffer is not used and number of bytes to read/write must be integer multiple of 512. |
| FA_OPEN_EXISTING | Opens the file. The function fails if the file does not exist. |
| FA_CREATE_ALWAYS | Creates a new file. If the file exists, it is truncated and overwritten. |
| FA_OPEN_ALWAYS | Opens the file, if it exists. If the file does not exist, the function creates the file. |
To start to use the FatFs module, prepare a work area (FATFS structure), clear the structure and store the address to the global variable 'FatFs' to allocate the work area to the FatFs module. Then the FatFs module can work.
Flags FA_WRITE, FA_CREATE_ALWAYS, FA_OPEN_ALWAYS are not supported in read-only configuration. Flag FA_UNBUFFERED is not supported in Tiny-FatFs.
void main ()
{
FATFS fs; // FatFs work area
FIL fsrc, fdst; // file structures
BYTE fbuff[512*2]; // file r/w buffers (not required for Tiny-FatFs)
BYTE buffer[4096]; // file copy buffer
FRESULT res; // FatFs function common result code
WORD br, bw; // File R/W count
// Activate FatFs module
memset(&fs, 0, sizeof(FATFS));
FatFs = &fs;
// Open source file
fsrc.buffer = fbuff+0; // (not required for Tiny-FatFs)
res = f_open(&fsrc, "/srcfile.dat", FA_OPEN_EXISTING | FA_READ);
if (res) die(res);
// Create destination file
fdst.buffer = fbuff+512; // (not required for Tiny-FatFs)
res = f_open(&fdst, "/dstfile.dat", FA_CREATE_ALWAYS | FA_WRITE);
if (res) die(res);
// Copy source to destination
for (;;) {
res = f_read(&fsrc, buffer, sizeof(buffer), &br);
if (res) die(res);
if (br == 0) break;
res = f_write(&fdst, buffer, br, &bw);
if (res) die(res);
if (bw < br) break;
}
// Close all files
f_close(&fsrc);
f_close(&fdst);
// Deactivate FatFs module
FatFs = NULL;
}