14 : logging_category(log4c_category_get(
"radar.utils"))
19 : logging_category(f.logging_category),
20 fname(std::move(f.fname)),
21 fdesc(std::move(f.fdesc)),
27 File::File(log4c_category_t* logging_category)
28 : logging_category(logging_category)
39 const char* envfname = getenv(varname);
42 LOG_ERROR(
"$%s is not set", varname);
46 return open(envfname, mode, desc);
49 bool File::open(
const std::string& pathname,
const char* mode,
const char* desc)
59 fd = fopen(pathname.c_str(), mode);
63 LOG_ERROR(
"Cannot open %s (%s): %s", pathname.c_str(), desc, strerror(errno));
65 LOG_ERROR(
"Cannot open %s: %s", pathname.c_str(), strerror(errno));
70 if (desc) fdesc = desc;
83 ssize_t read = getline(&line, &len, fd);
90 string errmsg(
"cannot read ");
93 errmsg += strerror(errno);
95 throw runtime_error(errmsg);
101 if (line) free(line);
106 if (line) free(line);
111 if (::fread(buf, size, 1, fd) != 1)
116 string errmsg(
"read failed on ");
119 errmsg += strerror(errno);
120 throw runtime_error(errmsg);
125 void File::fseek(
size_t seek_par,
int origin)
127 if (::fseek(fd,seek_par,origin) == -1)
129 string errmsg(
"fseek failed on ");
132 errmsg += strerror(errno);
133 throw runtime_error(errmsg);
139 const char* res = getenv(envname);
141 return default_value;
144 FILE*
fopen_checked(
const char* fname,
const char* mode,
const char* description)
146 FILE* res = fopen(fname, mode);
149 string errmsg(
"cannot open ");
152 errmsg += description;
159 errmsg += strerror(errno);
160 throw runtime_error(errmsg);
165 void str_split(
char* str,
const char* sep, std::function<
void (
const char* tok)> val_cb)
170 char* tok = strtok_r(str, sep, &saveptr);
171 if (tok == NULL)
break;
bool fread(void *buf, size_t size)
Performs a fread on the file, throwing an exception if anything goes wrong.
void read_lines(std::function< void(char *, size_t)> line_cb)
Read the file line by line, calling line_cb on each line read.
FILE * fopen_checked(const char *fname, const char *mode, const char *description)
A wrapper of fopen that throws an exception if it cannot open the file.
void str_split(char *str, const char *sep, std::function< void(const char *tok)> val_cb)
Split a string in tokens, skipping the given separator characters.
bool open_from_env(const char *varname, const char *mode, const char *desc=nullptr)
Opens a file taking its name from the environment variable envname.
const char * getenv_default(const char *envname, const char *default_value)
A wrapper of getenv, that returns 'default_value' if the given environment name is not defined...
bool open(const std::string &fname, const char *mode, const char *desc=nullptr)
Opens a file by its pathname.