C語言讀取通達信資料

C羽言發表於2024-04-18

因為無法事先知道資料的行數,只能透過計算得到,所以陣列建立只能透過動態分配記憶體。

一個解決方案是,我只想讀取最後1000行,那麼陣列就可以直接定義大小為1000,然後把檔案指標定位到倒數1000行。

#include <stdio.h>
#include <stdlib.h>

struct Stock {
    int date;
    float open;
    float high;
    float low;
    float close;
    float amount;
    int volume;
    int reserved;
};

int main() {
    FILE *fp = fopen("sz000001.day", "rb");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }
    fseek(fp, 0, SEEK_END);          // 定位檔案末尾
    long file_size = ftell(fp);      // 獲取檔案大小
    int line_count = file_size / 32; // 計算行數(假設每行32位元組)
    fseek(fp, 0, SEEK_SET);          // 回到檔案開頭
    // 動態分配記憶體
    struct Stock *stockArr = malloc(line_count * sizeof(struct Stock));
    if (stockArr == NULL) {
        perror("Error allocating memory");
        return -1;
    }
    int date, open, high, low, close, volume, reserved;
    float amount;
    int i = 0;
    for (int i = 0; i < line_count; i++) {
        // 讀取資料
        fread(&date, 4, 1, fp);
        fread(&open, 4, 1, fp);
        fread(&high, 4, 1, fp);
        fread(&low, 4, 1, fp);
        fread(&close, 4, 1, fp);
        fread(&amount, 4, 1, fp);
        fread(&volume, 4, 1, fp);
        fread(&reserved, 4, 1, fp);

        // printf("Date: %d, Open: %d, High: %d, Low: %d, Close: %d, Amount: %f, Volume: %d, Reserved: %d\n", date, open, high, low, close, amount,
        //        volume, reserved);
        stockArr[i].date = date;
        stockArr[i].open = open / 100.0;
        stockArr[i].high = high / 100.0;
        stockArr[i].low = low / 100.0;
        stockArr[i].close = close / 100.0;
        stockArr[i].amount = amount / 10000.0;
        stockArr[i].volume = volume;
        stockArr[i].reserved = reserved;

        // printf("Date: %d, Open: %.2f, High: %.2f, Low: %.2f, Close: %.2f, Amount: %.2f, Volume: %d, Reserved: %d\n", stockArr[i].date,
        //        stockArr[i].open, stockArr[i].high, stockArr[i].low, stockArr[i].close, stockArr[i].amount, stockArr[i].volume, stockArr[i].reserved);
    }
    printf("%d", stockArr[line_count-1].date);

    free(stockArr); // 釋放動態分配的記憶體
    fclose(fp);     // 釋放檔案

    return 0;
}

相關文章