[LTP] [PATCH 1/2] lib: safe_file_ops: Add SAFE_FILE_READ_STR()

Cyril Hrubis chrubis@suse.cz
Thu Apr 9 15:35:28 CEST 2026


Hi!
> diff --git a/lib/safe_file_ops.c b/lib/safe_file_ops.c
> index 8314c4b1b..2d163c0af 100644
> --- a/lib/safe_file_ops.c
> +++ b/lib/safe_file_ops.c
> @@ -160,6 +160,30 @@ void safe_file_scanf(const char *file, const int lineno,
>  	}
>  }
>  
> +void safe_file_read_str(const char *file, const int lineno,
> +                        const char *path, char *buf, size_t buf_size)
> +{
> +	FILE *f;
> +
> +	f = fopen(path, "r");
> +	if (!f) {
> +		tst_brkm_(file, lineno, TBROK | TERRNO, NULL,
> +		          "Failed to open FILE '%s' for reading", path);

We need a return; here in an unlikely case that someone would call this
from a test cleanup() callback.

> +	}
> +
> +	if (!fgets(buf, buf_size, f))
> +		buf[0] = 0;
> +
> +	size_t len = strlen(buf);
> +
> +	if (len && buf[len-1] == '\n')
> +		buf[len-1] = 0;
> +
> +	if (fclose(f)) {
> +		tst_brkm_(file, lineno, TBROK | TERRNO, NULL,
> +			"Failed to close FILE '%s'", path);
> +	}
> +}
>  
>  /*
>   * Try to parse each line from file specified by 'path' according
> -- 
> 2.52.0
> 
> 
> -- 
> Mailing list info: https://lists.linux.it/listinfo/ltp

-- 
Cyril Hrubis
chrubis@suse.cz


More information about the ltp mailing list