C++標準庫獲取時間、簡單的檔案操作
阿新 • • 發佈:2019-02-17
參考文章:
只是在以上的一堆,借鑑了一個簡單的用C++標準庫的日期及其格式化程式。
程式如下:(QT下面寫的)
#include <chrono> #include <ctime> #include <string> #include <iomanip> #include <iostream> #include <fstream> #include <sstream> using namespace std::chrono; using namespace std; int main(int argc, char *argv[]) { system_clock::time_point now = system_clock::now(); std::time_t time = system_clock::to_time_t(now); std::stringstream ss; //把時間資料格式轉換為字串 ss<<std::put_time(std::localtime(&time),"%Y-%m-%d %H:%M:%S "); cout<<ss.str()<<endl; ofstream wfile("data-"+ss.str()+".txt"); if(wfile.is_open()){ wfile<<"hello wk!!!"; //往檔案中寫資料 cout << "file open successed."; } else cout<<"file open failed!"; // auto t = chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // cout<< std::put_time(std::localtime(&t), "%Y-%m-%d %X")<<endl; // cout<< std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S")<<endl; return 0; }
但是,會報錯,put_time()不是標準庫中的函式,同樣的還有get_time().
查閱資料顯示,put_time()、get_time()在gcc5中才實現,gcc4中沒有,
錯誤:
ofstream data_file("datarecord-"+ss.str()+".txt");
。。。。。。。。。has initializer but incomplete type
原因:沒有包含操作檔案的標頭檔案#include<fstream>