DateUpdate.cpp
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
#include <stdio.h> | |
#include <string.h> | |
#include <string> | |
#include <iostream> | |
#include <fstream> | |
#include <time.h> | |
using namespace std; | |
long getCurrentTime(); //現在時刻を取得 | |
void showDateLogByLong(const long &time, const string &str); //デバック時刻表示 | |
bool isDailyFirstLogin(long currentTime); //毎日の最初のログイン状態確認 | |
void writeLastLoginTime(const long currentTime); //ログイン時間の書き込み | |
long readLastLoginTime(); //過去のログイン時間の読み込み | |
string FILE_NAME = "LastLoginTime.txt"; | |
int main() | |
{ | |
long currentTime = getCurrentTime(); | |
if(isDailyFirstLogin(currentTime)) | |
{ | |
cout << "更新する" << endl; | |
writeLastLoginTime(currentTime); | |
} else { | |
cout << "更新しない" << endl; | |
} | |
return 0; | |
} | |
//毎日の最初のログイン状態確認 | |
//更新日時よりも過去にログインしていたら trueを返す | |
bool isDailyFirstLogin(long currentTime) | |
{ | |
const long updateSec = 21600; //example: 06:00 → 6 * 3600 = 21600 | |
const long lastLoginTime = readLastLoginTime(); | |
showDateLogByLong(currentTime, "現在時刻の表示"); | |
showDateLogByLong(lastLoginTime, "最後にガチャを行った時刻"); | |
//最新(今日 or 昨日)の年月日入りの更新時刻を求めるため現在時刻を減算 | |
currentTime -= updateSec; | |
//年月日未満の値を初期化 | |
struct tm *currentDate = localtime(¤tTime); | |
currentDate->tm_hour = 0; | |
currentDate->tm_min = 0; | |
currentDate->tm_sec = 0; | |
//年月日入り更新時刻を作成 | |
const long updateTime = mktime(currentDate) + updateSec; | |
showDateLogByLong(updateTime, "年月日入り更新時刻"); | |
return lastLoginTime < updateTime; | |
} | |
//デバック時刻表示 | |
void showDateLogByLong(const long &time, const std::string &str) | |
{ | |
struct tm *timeTm = localtime(&time); | |
char *date = asctime(timeTm); | |
date[(int)strlen(date) - 1] = '\0'; | |
printf("%s %s\n", date, str.c_str()); | |
} | |
//現在時刻を取得 | |
long getCurrentTime() | |
{ | |
time_t now = time(NULL); | |
struct tm *nowDate = localtime(&now); | |
return mktime(nowDate); | |
} | |
//ログイン時間の書き込み | |
void writeLastLoginTime(const long currentTime) | |
{ | |
ofstream ofs; | |
ofs.open(FILE_NAME, ios::out|ios::binary|ios::trunc); | |
if (!ofs) { | |
cout << "書き込み失敗 ファイル " << FILE_NAME << " が開けません。終了します。" << endl; | |
exit(0); | |
} | |
ofs << currentTime << std::endl; | |
ofs.close(); | |
} | |
//過去のログイン時間の読み込み | |
long readLastLoginTime() | |
{ | |
ifstream ifs( FILE_NAME, ios::in | ios::binary ); | |
if (!ifs){ | |
cout << "読み込み失敗 ファイル " << FILE_NAME << " が開けません。 0を返します。" << endl; | |
return 0; | |
} | |
std::string str; | |
ifs >> str; | |
long readLast = stol(str); | |
ifs.close(); | |
return readLast; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment