c++ファイルio操作練習の書き込みログファイルと読み出しパラメータプロファイル
3851 ワード
初めてc++を学んで、菜鳥は1つ、プロジェクトはLinuxの下でファイルioの操作の流れを学ぶ必要があって、主にログファイルを書くこととパラメータの配置ファイルを読み取ることで、他の人のいくつかの方法を探して、簡単で分かりやすいものを選んで、記録します.
//
string GetSystemTime()
{
time_t tNowTime;
time(&tNowTime);
tm *tLocalTime = localtime(&tNowTime);
char szTime[30] = {'\0'};
strftime(szTime,30,"[%Y-%m-%d %H:%M:%S] ",tLocalTime);
string strTime = szTime;
return strTime;
}
//
bool readConfigFile(const char* cfgfilepath,const string & key, string & value1)
{
fstream cfgFile;
cfgFile.open(cfgfilepath);//
if(!cfgFile.is_open())
{
cout<<"can not open cfg file!"<return false;
}
char tmp[100];
while(!cfgFile.eof())//
{
cfgFile.getline(tmp,100);// 100 ,100
string line(tmp);
size_t pos = line.find('=');// “=” , key value
if(pos==string::npos)
return false;
string tmpKey = line.substr(0,pos);// =
if(key==tmpKey)
{
value1 = line.substr(pos+1);// =
return true;
}
}
cfgFile.close();
return false;
}
int main(int argc, char **argv)
{
ofstream fout("log.txt",ios::app);// , ios::app
fout <"start..."<< endl;
fout.close();
const char* cfgfilepath="config.cfg";
const string key_X="X";
string value_X="";
float X=0;
readConfigFile(cfgfilepath,key_X,value_X);
X=atof(value_X.c_str());//string float
return 0;
}