首先需要包含头文件
定义函数double *read_file(char *filename, int *size),接收文件名和文本中行数的指针参数。
在函数中,打开文件,首先检查是否存在。
统计文件中的行数,并动态分配足够的内存。
再次打开文件,以读取模式读取文件内容并将其存储在数组中。
关闭文件并返回指向数组的指针及其大小。
下面是示例代码:
#include
#include
double *read_file(char *filename, int *size) {
FILE *fp;
double *array;
double value;
int i = 0;
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error: File not found!\n");
exit(1);
}
*size = 0;
while (fscanf(fp, "%lf", &value) != EOF) {
++*size;
}
rewind(fp);
array = (double *) malloc(*size * sizeof(double));
while (fscanf(fp, "%lf", &value) != EOF) {
array[i] = value;
++i;
}
fclose(fp);
return array;
}
int main() {
double *data;
int size;
data = read_file("data.txt", &size);
printf("File contains %d values:\n", size);
for (int i = 0; i < size; ++i) {
printf("%.2f ", data[i]);
}
printf("\n");
free(data);
return 0;
}
在上面的示例中,我们先读取了data.txt文件中的所有数值,然后按照文件中的顺序存储在double数组中,最后输出数组中的每个元素,并在最后释放内存。