Skip to content

Instantly share code, notes, and snippets.

@wdanxna
Created December 14, 2018 09:10
Show Gist options
  • Save wdanxna/2726fe51f1f83fc255b594a744b4be91 to your computer and use it in GitHub Desktop.
Save wdanxna/2726fe51f1f83fc255b594a744b4be91 to your computer and use it in GitHub Desktop.
create & append string into a file
struct FileAppender {
std::ofstream _file;
std::mutex _lock;
explicit FileAppend(const std::string& filename) {
_file.open(filename.c_str(), std::ios_base::app);
}
virtual ~FileAppend() {
_file.flush();
_file.close();
}
void append(const std::string& content) {
std::lock_guard<std::mutex> lock(_lock);
_file << content;
}
void appendNow(const std::string& content) {
append(content);
_file.flush();
}
void flush() {
_file.flush();
}
void append(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
std::ostringstream ss;
while (*fmt != '\0') {
if (*fmt == '%') {
fmt++;
switch (*fmt) {
case 'd':
ss << va_arg(args, int);
break;
case 'f':
ss << va_arg(args, float);
case 'l':
if (*(fmt+1) == 'd') {fmt++;}
ss << va_arg(args, long);
default:
//not supported yet
assert(false);
}
} else {
ss << *fmt;
}
fmt++;
}
va_end(args);
std::lock_guard<std::mutex> lock(_lock);
_file << ss.str();
}
void appendLine(const std::string& content) {
std::lock_guard<std::mutex> lock(_lock);
_file << content;
_file << "\n";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment