littlefs-project / littlefs

A little fail-safe filesystem designed for microcontrollers
BSD 3-Clause "New" or "Revised" License
4.9k stars 770 forks source link

File creation with full path in the name #973

Closed josesimoes closed 2 months ago

josesimoes commented 2 months ago

Hey!

A few questions regarding paths and file/directory creation, please.

Is it OK to call lfs_file_opencfg() specifying the file name the full path to it? Like temp/testdir/file1.txt. Are the directories in the path created?

I've tried to create the directory first with lfs_mkdir(fs, "temp/testdir") but it returns LFS_ERR_NOENT.

What am I doing wrong?

Thanks!

geky commented 2 months ago

Hi @josesimoes,

lfs_file_open, lfs_mkdir, etc, will only create the last name in a file path.

So you need to create all of the parent directories first:

lfs_mkdir(fs, "temp") => 0;
lfs_mkdir(fs, "temp/testdir") => 0;
lfs_file_opencfg(fs, file, "temp/testdir/file1.txt") => 0;

When utils such as mkdir -p do this for you, it's usually implemented at the application level because it's a bit complicated and not needed by all applications: https://github.com/coreutils/coreutils/blob/15de627decf2e357c246c23a1574ba216530a6f0/lib/mkdir-p.c#L156

josesimoes commented 2 months ago

Understood. I have it working now. Thanks!

PS: not sure how relevant it is, but maybe it's worthy adding a note on the documentation about this...