因为无法事先知道数据的行数,只能通过计算得到,所以数组创建只能通过动态分配内存。
一个解决方案是,我只想读取最后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;
}
标签:fp,读取,stockArr,int,fread,C语言,通达信,date,close From: https://www.cnblogs.com/yuyanc/p/18144052