Skip to content

Commit c2e52af

Browse files
tridgepeterbarker
authored andcommitted
AP_Filesystem: make fgets() much more efficient
normally fgets is on a buffered FILE handle. For AP_Filesystem we use an unbuffered file descriptor. This means we were reading one byte at a time from the file this uses lseek to make fgets() much more efficient by reading the max buffer size at a time in the file
1 parent 0d12cc7 commit c2e52af

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

libraries/AP_Filesystem/AP_Filesystem.cpp

+19-7
Original file line numberDiff line numberDiff line change
@@ -321,19 +321,31 @@ bool AP_Filesystem::fgets(char *buf, uint8_t buflen, int fd)
321321
{
322322
const Backend &backend = backend_by_fd(fd);
323323

324+
// we will need to seek back to the right location at the end
325+
auto offset_start = backend.fs.lseek(fd, 0, SEEK_CUR);
326+
if (offset_start < 0) {
327+
return false;
328+
}
329+
330+
auto n = backend.fs.read(fd, buf, buflen);
331+
if (n <= 0) {
332+
return false;
333+
}
334+
324335
uint8_t i = 0;
325-
for (; i<buflen-1; i++) {
326-
if (backend.fs.read(fd, &buf[i], 1) <= 0) {
327-
if (i==0) {
328-
return false;
329-
}
330-
break;
331-
}
336+
for (; i < n; i++) {
332337
if (buf[i] == '\r' || buf[i] == '\n') {
333338
break;
334339
}
335340
}
336341
buf[i] = '\0';
342+
343+
// get back to the right offset
344+
if (backend.fs.lseek(fd, offset_start+i+1, SEEK_SET) != offset_start+i+1) {
345+
// we need to fail if we can't seek back or the caller may loop or get corrupt data
346+
return false;
347+
}
348+
337349
return true;
338350
}
339351

0 commit comments

Comments
 (0)