我需要编写一个程序来读取各种文件并将信息存储到数组中。我将使用双打执行矩阵乘法。关于文件的格式;第一行包含矩阵的大小。接下来的几行是矩阵的行,其中每个元素用空格分隔。
格式:
<number of rows> <number of columns>
<double> <double> ... <double>
<double> <double> ... <double>
.
.
.
<double> <double> ... <double>
以下是几个示例文件:
3 4
1.20 2.10 4.30 2.10
3.30 3.10 5.20 2.80
1.10 0.60 4.70 4.90
或
5 5
1.20 2.10 4.30 2.10 6.70
3.30 3.10 5.20 2.80 3.20
1.10 0.60 4.70 4.90 9.10
3.30 3.10 5.20 2.80 3.20
1.10 0.60 4.70 4.90 7.10
目前我的代码如下:
float** readFile(char* fp)
{
float** matrix = (float**)malloc(M*N*sizeof(float));
fp = fopen(fp, "r");
if (fp == NULL)
{
fprintf(stderr, "Can't open the file\n");
exit(1)
}
int i = 0;
int m, n;
fscanf(fp, "%d %d", m, n);
while (fscanf(fp, "");
{
i++;
}
fclose(fp);
return matrix;
}
我正在调用这样的函数:
float** A = readFile(argv[1]);
显然,由于fscanf在读取文件时缺少参数,因此目前无效。如何使用fscanf将值读入矩阵?
答案 0 :(得分:2)
修改此功能
float** readFile(char* file)
{
FILE *fp;
float** matrix = (float**)malloc(M*N*sizeof(float));
fp = fopen(file, "r");
if (fp == NULL)
{
fprintf(stderr, "Can't open the file\n");
exit(1)
}
int i = 0;
int m, n;
fscanf(fp, "%d %d", m, n);
while (fgets(line,size(line),fp)!=NULL) //read file line by line
{
使用strtok()将行拆分为具有分隔符空间的标记 使用strtof()将字符串转换为float
}
fclose(fp);
return matrix;
}
答案 1 :(得分:1)
简单来说,让我们使用一维数组。这是你的工作代码。
#include <stdio.h>
#include <stdlib.h>
float* readFile(char* fp, int *m, int *n)/* return the dimension defined in file*/
{
FILE *file = fopen(fp, "r");
if (file == NULL)
{
fprintf(stderr, "Can't open the file\n");
exit(1);
}
int i = 0, j = 0;
fscanf(file, "%d %d[^\n]\n", m, n);
float* matrix = (float*)malloc((*m)*(*n)*sizeof(float));
float f;
for (i = 0; i < *m ; ++i)
for (j = 0; j < *n ; ++j)
{
fscanf(file, "%f", (matrix + i * (*n) + j));
}
fclose(file);
return matrix;
}
int main()
{
int m, n, i, j;
float *a = readFile("a.dat", &m, &n); /* i named your data file a.dat*/
for (i = 0; i < m ; ++i)
{
for (j = 0; j < n ; ++j)
printf("%f ", *(a + i * n + j));
printf("\n");
}
free(a);
}
/* this is the output */
1.200000 2.100000 4.300000 2.100000 6.700000
3.300000 3.100000 5.200000 2.800000 3.200000
1.100000 0.600000 4.700000 4.900000 9.100000
3.300000 3.100000 5.200000 2.800000 3.200000
1.100000 0.600000 4.700000 4.900000 7.100000
答案 2 :(得分:0)
这是另一个将数据读入动态分配的二维数组的版本:
#include <stdio.h>
#include <stdlib.h>
float** arralloc(int r, int c) {
int i;
float** arr = (float**) malloc(r*sizeof(float*));
for (i = 0; i < r; i++)
arr[i] = (float*) malloc(c*sizeof(float));
return arr;
}
int main(void)
{
int c,r,i,j;
FILE *file = fopen("file", "r");
fscanf(file, "%d %d\n", &r, &c);
float** arr = arralloc(r,c);
for (i = 0; i < r; i++){
for (j = 0; j < c; j++){
fscanf(file, "%f", &arr[i][j]);
printf("%.2f ", arr[i][j]);
}
printf("\n");
}
fclose(file);
free(arr);
}