|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Endress+Hauser AG |
| 3 | + * Copyright (c) 2025 Arch-Embedded B.V. |
| 4 | + * |
| 5 | + * SPDX-License-Identifier: Apache-2.0 |
| 6 | + */ |
| 7 | + |
| 8 | +#include <zephyr/device.h> |
| 9 | +#include <zephyr/fs/fs.h> |
| 10 | +#include <zephyr/kernel.h> |
| 11 | +#include <zephyr/logging/log.h> |
| 12 | +#include <zephyr/storage/disk_access.h> |
| 13 | + |
| 14 | +LOG_MODULE_REGISTER(main, LOG_LEVEL_INF); |
| 15 | + |
| 16 | +#define AUTOMOUNT_NODE DT_NODELABEL(ext2fs1) |
| 17 | +#define MOUNT_POINT DT_PROP(AUTOMOUNT_NODE, mount_point) |
| 18 | + |
| 19 | +FS_FSTAB_DECLARE_ENTRY(AUTOMOUNT_NODE); |
| 20 | + |
| 21 | +#define FILE_PATH MOUNT_POINT "/hello.txt" |
| 22 | + |
| 23 | +int main(void) |
| 24 | +{ |
| 25 | + struct fs_file_t file; |
| 26 | + int rc; |
| 27 | + static const char data[] = "Hello"; |
| 28 | + /* You can get direct mount point to automounted node too */ |
| 29 | + struct fs_mount_t *auto_mount_point = &FS_FSTAB_ENTRY(AUTOMOUNT_NODE); |
| 30 | + struct fs_dirent stat; |
| 31 | + |
| 32 | + fs_file_t_init(&file); |
| 33 | + |
| 34 | + rc = fs_open(&file, FILE_PATH, FS_O_CREATE | FS_O_WRITE); |
| 35 | + if (rc != 0) { |
| 36 | + LOG_ERR("Accessing filesystem failed"); |
| 37 | + return rc; |
| 38 | + } |
| 39 | + |
| 40 | + rc = fs_write(&file, data, strlen(data)); |
| 41 | + if (rc != strlen(data)) { |
| 42 | + LOG_ERR("Writing filesystem failed"); |
| 43 | + return rc; |
| 44 | + } |
| 45 | + |
| 46 | + rc = fs_close(&file); |
| 47 | + if (rc != 0) { |
| 48 | + LOG_ERR("Closing file failed"); |
| 49 | + return rc; |
| 50 | + } |
| 51 | + |
| 52 | + /* You can unmount the automount node */ |
| 53 | + rc = fs_unmount(auto_mount_point); |
| 54 | + if (rc != 0) { |
| 55 | + LOG_ERR("Failed to do unmount"); |
| 56 | + return rc; |
| 57 | + }; |
| 58 | + |
| 59 | + /* And mount it back */ |
| 60 | + rc = fs_mount(auto_mount_point); |
| 61 | + if (rc != 0) { |
| 62 | + LOG_ERR("Failed to remount the auto-mount node"); |
| 63 | + return rc; |
| 64 | + } |
| 65 | + |
| 66 | + /* Is the file still there? */ |
| 67 | + rc = fs_stat(FILE_PATH, &stat); |
| 68 | + if (rc != 0) { |
| 69 | + LOG_ERR("File status check failed %d", rc); |
| 70 | + return rc; |
| 71 | + } |
| 72 | + |
| 73 | + LOG_INF("Filesystem access successful"); |
| 74 | + |
| 75 | + return 0; |
| 76 | +} |
0 commit comments