Last active
November 27, 2015 12:23
-
-
Save xylcbd/289a69c0fed9099d0de1 to your computer and use it in GitHub Desktop.
scope exit lambda
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
namespace cxxdetail | |
{ | |
template <typename FuncType> | |
class InnerScopeExit | |
{ | |
public: | |
InnerScopeExit(const FuncType _func) :func(_func){} | |
~InnerScopeExit(){ if (!dismissed){ func(); } } | |
private: | |
FuncType func; | |
bool dismissed = false; | |
}; | |
template <typename F> | |
InnerScopeExit<F> MakeScopeExit(F f) { | |
return InnerScopeExit<F>(f); | |
}; | |
} | |
#define DO_STRING_JOIN(arg1, arg2) arg1 ## arg2 | |
#define STRING_JOIN(arg1, arg2) DO_STRING_JOIN(arg1, arg2) | |
#define SCOPEEXIT(code) auto STRING_JOIN(scope_exit_object_, __LINE__) = cxxdetail::MakeScopeExit([&](){code;}); | |
void copy(const char* src_file_path,const char* dst_file_path) | |
{ | |
FILE* fp_src = fopen(src_file_path, "rb"); | |
SCOPEEXIT(if (fp_src){ fclose(fp_src); }); | |
if (!fp_src) | |
{ | |
return; | |
} | |
//get file length | |
fseek(fp_src, 0, SEEK_SET); | |
fseek(fp_src, 0, SEEK_END); | |
const long longBytes = ftell(fp_src); | |
if (longBytes <= 0) | |
{ | |
return; | |
} | |
fseek(fp_src, 0, SEEK_SET); | |
//do copy | |
FILE* fp_dst = fopen(dst_file_path, "wb"); | |
SCOPEEXIT(if (fp_dst){ fclose(fp_dst); }); | |
if (!fp_dst) | |
{ | |
return; | |
} | |
const int buffer_len = 4*1024; | |
char buffer[buffer_len]; | |
int read_len = 0; | |
while ((read_len = fread(buffer, 1, buffer_len, fp_src)) > 0) | |
{ | |
fwrite(buffer, 1, read_len, fp_dst); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment