[Concept,01/15] sandbox: Add a function to read a line from a file
Commit Message
From: Simon Glass <sjg@chromium.org>
Provide a version of fgets() which works on file descriptors. This can
be used to read lines from a file, as will be needed for the ulib
test-program.
Signed-off-by: Simon Glass <sjg@chromium.org>
---
arch/sandbox/cpu/os.c | 32 ++++++++++++++++++++++++++++++++
include/os.h | 14 ++++++++++++++
2 files changed, 46 insertions(+)
@@ -150,6 +150,38 @@ int os_unlink(const char *pathname)
return unlink(pathname);
}
+char *os_fgets(char *str, int size, int fd)
+{
+ char *s = str;
+ int n = size - 1;
+ int i;
+
+ if (n <= 0 || !str)
+ return NULL;
+
+ for (i = 0; i < n; i++) {
+ ssize_t ret;
+ char c;
+
+ ret = read(fd, &c, 1);
+ if (ret <= 0) {
+ /* EOF or error */
+ if (!i)
+ return NULL;
+ break;
+ }
+
+ *s++ = c;
+
+ if (c == '\n')
+ break;
+ }
+
+ *s = '\0';
+
+ return str;
+}
+
void os_exit(int exit_code)
{
exit(exit_code);
@@ -106,6 +106,20 @@ int os_isatty(int fd);
*/
int os_unlink(const char *pathname);
+/**
+ * os_fgets() - read a string from a file stream
+ *
+ * Reads at most @size - 1 characters from the stream and stores them in str.
+ * Reading stops after an EOF or a newline. If a newline is read, it is
+ * stored in str. A terminating nul byte is appended.
+ *
+ * @str: Buffer to store the string
+ * @size: Maximum number of characters to read (including null terminator)
+ * @fd: File descriptor to read from
+ * Return: str on success, NULL on error, or EOF with no characters read
+ */
+char *os_fgets(char *str, int size, int fd);
+
/** os_persistent_fname() - Find the path to a test file
*
* @buf: Buffer to hold path