Morse Micro IoT SDK  2.10.4
fileio.c
Go to the documentation of this file.
1/*
2 * Copyright 2023 Morse Micro
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
28#include <stdio.h>
29#include <sys/unistd.h>
30#include <sys/fcntl.h>
31#include <sys/errno.h>
32
37void app_init(void)
38{
39 printf("\n\nFile I/O Example (Built " __DATE__ " " __TIME__ ")\n\n");
40
41 /* Open a file for reading - calling open() the first time automatically initializes
42 * The file I/O subsystem and links in the required modules. */
43 int fd = open("test.txt", O_RDONLY);
44 if (fd < 0)
45 {
46 /* We got an error, check for @c EINVAL which signifies File I/O is not supported */
47 if (errno == ENOENT)
48 {
49 /* We got a file not found error, so simply create the file */
50 printf("File test.txt not found, creating...");
51 fd = open("test.txt", O_RDWR | O_CREAT);
52 if (fd >= 0)
53 {
54 char message[] = "G'day World!\n";
55 int count = write(fd, message, sizeof(message));
56 close(fd);
57 if (count >= 0)
58 {
59 printf("%d bytes written!\n"
60 "Run application again to see what was written.\n",
61 count);
62 }
63 else
64 {
65 printf("Error %d!\n Failed to write to file!\n", errno);
66 }
67 }
68 else
69 {
70 printf("Failed!\n");
71 }
72 }
73 else
74 {
75 printf("File I/O is currently not supported on this platform!\n");
76 }
77 }
78 else
79 {
80 /* File successfully opened, read contents */
81 char buffer[64];
82 int count = read(fd, buffer, sizeof(buffer) - 1);
83 close(fd);
84 if (count >= 0)
85 {
86 /* Ensure buffer is null terminated */
87 buffer[count] = 0;
88 printf("%d bytes read!\nContents: %s\n", count, buffer);
89 }
90 else
91 {
92 printf("Error %d!\nFailed to read from file!\n", errno);
93 }
94 }
95}
void app_init(void)
Main entry point to the application.
Definition: fileio.c:37