Created
December 14, 2018 09:10
-
-
Save wdanxna/2726fe51f1f83fc255b594a744b4be91 to your computer and use it in GitHub Desktop.
create & append string into a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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