C++向檔案中寫入資料
阿新 • • 發佈:2018-12-31
#include<iostream>
#include<fstream>
#include<ctime>
using namespace std;
int main()
{
time_t time_now; //定義一個time_t結構的物件
time(&time_now); //獲取系統當前的日曆時間
tm timep; //時間結構體
localtime_s(&timep,&time_now); //將日曆時間轉換為本地時間儲存在tm結構體物件中
ofstream fileOpen; //定義ofstream 物件
char path[200],FilePath[2000];
fileOpen.open(path,ofstream::app);
if(!fileOpen)
{
cout<<"沒有開啟檔案!"<<endl;
fileOpen.close();
return 0;
}
char buf[10]={'I','L','o','v','e','y','o','u','!'};
sprintf_s(FilePath,2000,"%d/%d/%d %d:%d:%d %s \n",
timep.tm_year+1900,
timep.tm_mon+1,
timep.tm_mday,
timep.tm_hour,
timep.tm_min,
timep.tm_sec,
buf);
fileOpen<<FilePath;
fileOpen.close();
return 0;
}
#include<fstream>
#include<ctime>
using namespace std;
int main()
{
time_t time_now; //定義一個time_t結構的物件
time(&time_now); //獲取系統當前的日曆時間
tm timep; //時間結構體
localtime_s(&timep,&time_now); //將日曆時間轉換為本地時間儲存在tm結構體物件中
ofstream fileOpen; //定義ofstream 物件
char path[200],FilePath[2000];
sprintf_s(path,200,"Log\\%d年%d月.txt",timep.tm_year+1900,timep.tm_mon);//注意Log資料夾必須已經存在
//否則將導致檔案打不開
fileOpen.open(path,ofstream::app);
if(!fileOpen)
{
cout<<"沒有開啟檔案!"<<endl;
fileOpen.close();
return 0;
}
char buf[10]={'I','L','o','v','e','y','o','u','!'};
sprintf_s(FilePath,2000,"%d/%d/%d %d:%d:%d %s \n",
timep.tm_mon+1,
timep.tm_mday,
timep.tm_hour,
timep.tm_min,
timep.tm_sec,
buf);
fileOpen<<FilePath;
fileOpen.close();
return 0;
}