diff options
author | Chris Xiong <chirs241097@gmail.com> | 2018-04-09 22:42:45 +0800 |
---|---|---|
committer | Chris Xiong <chirs241097@gmail.com> | 2018-04-09 22:42:45 +0800 |
commit | 6bdb9028af9a5256fbb47b942843e49aef7e3aa1 (patch) | |
tree | a2346e35e36a3fcb016cb7ab65bcbcb84dede1bf /utils.cpp | |
download | lightsd-6bdb9028af9a5256fbb47b942843e49aef7e3aa1.tar.xz |
Initial commit.
Diffstat (limited to 'utils.cpp')
-rw-r--r-- | utils.cpp | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/utils.cpp b/utils.cpp new file mode 100644 index 0000000..8dc5f5a --- /dev/null +++ b/utils.cpp @@ -0,0 +1,65 @@ +#include <cstdio> +#include <cstring> +#include <cerrno> +#include <cctype> +#include "utils.hpp" +int readint(const char* path) +{ + FILE* f=fopen(path,"r"); + if(!f)return LOG('W',"failed to open %s for reading: %d",path,errno),0; + char buf[16]; + fgets(buf,16,f); + buf[15]=0; + fclose(f); + return atoi(buf); +} +float readfloat(const char* path) +{ + FILE* f=fopen(path,"r"); + if(!f)return LOG('W',"failed to open %s for reading: %d",path,errno),0; + char buf[16]; + fgets(buf,16,f); + buf[15]=0; + fclose(f); + return atof(buf); +} +std::string readstr(const char* path) +{ + FILE* f=fopen(path,"r"); + if(!f)return LOG('W',"failed to open %s for reading: %d",path,errno),""; + char buf[256]; + fgets(buf,256,f); + buf[255]=0; + fclose(f); + return std::string(buf); +} +void writeint(const char* path,int v) +{ + FILE* f=fopen(path,"w"); + if(!f){LOG('W',"failed to open %s for writing",path);return;} + fprintf(f,"%d",v); + fclose(f); +} +std::string trim(std::string s) +{ + size_t st=0; + for(;st<s.length()&&isspace(s[st]);++st); + if(st==s.length())return ""; + s=s.substr(st); + while(s.length()&&isspace(s.back()))s.pop_back(); + return s; +} +void split(std::string s,char c,std::vector<std::string>& v) +{ + v.clear(); + for(size_t anch=0;;) + { + std::string sec; + if(s.find(c,anch)==std::string::npos) + sec=s.substr(anch); + else sec=s.substr(anch,s.find(c,anch)-anch); + v.push_back(sec); + if(s.find(c,anch)==std::string::npos)break; + anch=s.find(c,anch)+1; + } +} |