From fc5ebe217fc2712b60dfaa5d96b66386a041dd42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD=20=D0=94=D0=BE=D0=BD=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=BA=D0=BE?= Date: Sun, 8 Apr 2018 01:00:46 +0300 Subject: [PATCH] wiretap: Add a file_gets variant that returns a pointer to the NUL terminator MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When using file_gets it's very difficult to determine how many characters were read, because you can't distinguish between an embedded NUL and a short line (note that the last line in a file may not have an LF at the end). While it's still possible to do it via prefilling the buffer with non-zero values, doing that is cumbersome, inefficient and error-prone. This new function makes the task much easier. The "p" in the name is meant to be reminiscent of the "p" in stpcpy. Change-Id: I468d5ee71e3b6289925860651ba61b369301b3c9 Reviewed-on: https://code.wireshark.org/review/27333 Petri-Dish: Stig Bjørlykke Tested-by: Petri Dish Buildbot Reviewed-by: Stig Bjørlykke --- wiretap/file_wrappers.c | 15 ++++++++++++--- wiretap/file_wrappers.h | 1 + 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/wiretap/file_wrappers.c b/wiretap/file_wrappers.c index cae0cfc491..daf0798ce7 100644 --- a/wiretap/file_wrappers.c +++ b/wiretap/file_wrappers.c @@ -1398,8 +1398,9 @@ file_getc(FILE_T file) return ret < 1 ? -1 : buf[0]; } +/* Like file_gets, but returns a pointer to the terminating NUL. */ char * -file_gets(char *buf, int len, FILE_T file) +file_getsp(char *buf, int len, FILE_T file) { guint left, n; char *str; @@ -1461,9 +1462,17 @@ file_gets(char *buf, int len, FILE_T file) buf += n; } while (left && eol == NULL); - /* found end-of-line or out of space -- terminate string and return it */ + /* found end-of-line or out of space -- add a terminator and return + a pointer to it */ buf[0] = 0; - return str; + return buf; +} + +char * +file_gets(char *buf, int len, FILE_T file) +{ + if (!file_getsp(buf, len, file)) return NULL; + return buf; } int diff --git a/wiretap/file_wrappers.h b/wiretap/file_wrappers.h index 64e0b6b166..40fe9c9788 100644 --- a/wiretap/file_wrappers.h +++ b/wiretap/file_wrappers.h @@ -26,6 +26,7 @@ WS_DLL_PUBLIC int file_read(void *buf, unsigned int count, FILE_T file); WS_DLL_PUBLIC int file_peekc(FILE_T stream); WS_DLL_PUBLIC int file_getc(FILE_T stream); WS_DLL_PUBLIC char *file_gets(char *buf, int len, FILE_T stream); +WS_DLL_PUBLIC char *file_getsp(char *buf, int len, FILE_T stream); WS_DLL_PUBLIC int file_eof(FILE_T stream); WS_DLL_PUBLIC int file_error(FILE_T fh, gchar **err_info); extern void file_clearerr(FILE_T stream);