sandbox: Add a function to read a line from a file

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>
This commit is contained in:
Simon Glass
2025-09-04 12:57:37 -06:00
parent b4e719cf47
commit 7735072d66
2 changed files with 46 additions and 0 deletions

View File

@@ -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);

View File

@@ -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