[PATCH v1 3/4] ConfigFile: Convert to C++
Chris Johns
chrisj at rtems.org
Thu Dec 9 02:41:24 UTC 2021
On 9/12/21 2:15 am, Ryan Long wrote:
> ---
> tester/covoar/ConfigFile.cc | 79 +++++++++++++++++----------------------------
> tester/covoar/ConfigFile.h | 2 +-
> 2 files changed, 31 insertions(+), 50 deletions(-)
>
> diff --git a/tester/covoar/ConfigFile.cc b/tester/covoar/ConfigFile.cc
> index c16b64a..5c8949e 100644
> --- a/tester/covoar/ConfigFile.cc
> +++ b/tester/covoar/ConfigFile.cc
> @@ -10,6 +10,10 @@
> #include <stdio.h>
Is this needed? I think reducing the C interfaces included would help the long
maintenance.
> #include <ctype.h>
>
> +#include <iostream>
> +#include <fstream>
> +#include <sstream>
> +
> namespace Configuration {
>
> FileReader::FileReader(
> @@ -24,43 +28,40 @@ namespace Configuration {
> }
>
> bool FileReader::processFile(
> - const char* const file
> + const std::string& file
> )
> {
> #define METHOD "FileReader::processFile - "
> - FILE * in;
> - char line[256];
> - char option[256];
> - char value[256];
> + #define MAX_LENGTH 256
> + std::ifstream in;
> + std::string line;
> + char option[MAX_LENGTH];
> + char value[MAX_LENGTH];
> int line_no;
> int i;
> int j;
>
> - if ( file == NULL ) {
> - fprintf( stderr, METHOD "NULL filename\n" );
> + if ( file.empty() ) {
> + std::cerr << METHOD << "Empty filename" << std::endl;
> return false;
> }
>
> - in = fopen( file, "r" );
> - if ( !in ) {
> - fprintf( stderr, METHOD "unable to open %s\n", file );
> + in.open( file );
> + if ( !in.is_open() ) {
> + std::cerr << METHOD << "unable to open " << file << std::endl;
> return false;
> }
>
> line_no = 0;
> - while (fgets(line, sizeof(line), in) != NULL) {
> + while ( std::getline( line, MAX_LENGTH ) ) {
> int length;
>
> line_no++;
>
> - length = (int) strlen( line );
> - if ( line[length - 1] != '\n' ) {
> - fprintf(
> - stderr,
> - "%s: line %d is too long",
> - file,
> - line_no
> - );
> + length = (int) line.length();
> + if ( length > MAX_LENGTH ) {
> + std::cerr << file << ": line " << line_no << " is too long"
> + << std::endl;
> continue;
> }
>
> @@ -96,14 +97,9 @@ namespace Configuration {
> if (line[0] == '\0')
> continue;
>
> - if (sscanf(line, "%s", option) != 1) {
> - fprintf(
> - stderr,
> - "%s: line %d is invalid: %s\n",
> - file,
> - line_no,
> - line
> - );
> + if (sscanf(line.c_str(), "%s", option) != 1) {
I suggest you use the C++ interface ..
https://en.cppreference.com/w/cpp/io/c/fscanf
> + std::cerr << file << ": line" << line_no << " is invalid: " << line
> + << std::endl;
Please make the repeated code a helper function with line number and line as args.
Chris
More information about the devel
mailing list