0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C言語で現在時刻をテキストファイルに書き込むプログラムを作成しました。

Last updated at Posted at 2023-10-01

現在時刻をテキストファイルに保存するプログラムです。
実行後にスペースキーを押すことで保存を行うことが可能です。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>

#define MAX_TIMESTAMPS 1000
#define DELAY_TIME 1000
typedef struct {
      time_t timestamp;
      long sys_val;
    }data_t;


void writeTimestampsToFile(const char* fileName, data_t* data, int count) {
    FILE* file = fopen(fileName, "w");
    if (file == NULL) {
        perror("ファイルを開けません");
        return;
    }
    time_t *timestamps;
    for (int i = 0; i < count; i++) {
        fprintf(file, "%d ",data[i].sys_val);
        fprintf(file, "%s", ctime(&data[i].timestamp));
    }
    fclose(file);
}
 
int main() {
    
    data_t *data = (data_t*)calloc(MAX_TIMESTAMPS, sizeof(data_t));
    time_t *timestamps = (time_t*)calloc(MAX_TIMESTAMPS, sizeof(time_t));
    if (timestamps == NULL) {
        perror("メモリを確保できません");
        return 1;
    }

    int currentIndex = 0;

    printf("スペースキーを押すとタイムスタンプを記録します。Ctrl-Cで終了します。\n");

    while (1) {
        time_t currentTime;
        time(&currentTime);
        timestamps[currentIndex] = currentTime;
        data[currentIndex].timestamp = currentTime;
        (data[currentIndex].sys_val) = rand();
        currentIndex = (currentIndex + 1) % MAX_TIMESTAMPS;
        if (_kbhit()) {
            char keyPressed = _getch();
            if (keyPressed == ' ') {
                printf("space\n");
                writeTimestampsToFile("time.txt", data, MAX_TIMESTAMPS);
            }
        }
        Sleep(DELAY_TIME);
    }
    // プログラムがCtrl-Cで終了する場合、すべてのタイムスタンプをファイルに書き込む
    free(timestamps);
    return 0;
}
0
1
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?