Morse Micro IoT SDK
2.9.7
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
37
void
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"
, count);
61
}
62
else
63
{
64
printf(
"Error %d!\n Failed to write to file!\n"
, errno);
65
}
66
}
67
else
68
{
69
printf(
"Failed!\n"
);
70
}
71
}
72
else
73
{
74
printf(
"File I/O is currently not supported on this platform!\n"
);
75
}
76
}
77
else
78
{
79
/* File successfully opened, read contents */
80
char
buffer[64];
81
int
count = read(fd, buffer,
sizeof
(buffer) - 1);
82
close(fd);
83
if
(count >= 0)
84
{
85
/* Ensure buffer is null terminated */
86
buffer[count] = 0;
87
printf(
"%d bytes read!\nContents: %s\n"
, count, buffer);
88
}
89
else
90
{
91
printf(
"Error %d!\nFailed to read from file!\n"
, errno);
92
}
93
}
94
}
app_init
void app_init(void)
Main entry point to the application.
Definition:
fileio.c:37
examples
fileio
src
fileio.c
Copyright 2021 Morse Micro