我正在嘗試編寫一個函數將文件中的數字讀入二維矩陣; mm_alloc()
函數是一個創建空矩陣的函數,並且該文件的第一行是矩陣的大小;但代碼似乎無法從文件中讀取,我的問題是什麼?我錯誤地使用fgets()
和sscanf()
?將文件中的數字讀入二維矩陣
double **mm_alloc(int size)
{
double **matrix;
int i;
matrix = (double **)malloc((size) * sizeof(double *));
for (i = 0; i < size; i++) {
matrix[i] = (double *)malloc(size);
}
return(matrix);
}
double **mm_read(char *filename, int *size)
{
FILE *myfile;
myfile = fopen(filename, "r");
char read[256];
fgets(read, 256, myfile);
sscanf(read, "%d", size);
int i, j;
double **Matrix;
Matrix = mm_alloc(*size);
for (i = 0; i < *size; i++) {
for (j = 0; j < *size; j++) {
fgets(read, 256, myfile);
sscanf(read, "%lf", &Matrix[i][j]);
}
}
fclose (myfile);
return(Matrix);
}
void mm_free(int size, double **matrix )
{
int i;
for (i = 0; i < size; i++) {
free(matrix[i]);
}
free(matrix);
}
void mm_print(int size, double **matrix)
{
int i, j;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
printf("%16f", matrix[i][j]);
}
printf("\n");
}
}
double **mm_swap(int size, double **matrix)
{
double **swap;
swap = mm_alloc(size);
int i, j;
for (i = 0; i < size; i++) {
for (j = 0; j < (size-2); j++) {
swap[i][j] = matrix[i][j+2];
swap[i][j+2] = matrix[i][j];
}
}
return(swap);
}
double **mm_matrix_mult(int size, double **matrix, double **transpose)
{
double **matrix_mult;
matrix_mult = mm_alloc(size);
int i, j, k;
double result;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
result = 0;
for (k = 0; k < size; k++) {
result += (matrix[i][k] * transpose[k][j]);
}
matrix_mult[i][j] = result;
}
}
return(matrix_mult);
}
int main()
{
char filename[256];
double **matrix=NULL;
double **swap_matrix=NULL;
double **results_matrix=NULL;
int size=0;
printf("Please enter the matrix data file name: ");
scanf("%s", filename);
matrix = mm_read(filename, &size);
swap_matrix = mm_swap(size, matrix);
results_matrix = mm_matrix_mult(size, matrix, swap_matrix);
mm_print(size, results_matrix);
mm_free(size, matrix);
mm_free(size, swap_matrix);
mm_free(size, results_matrix);
return(0);
}
文件內容:
4
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
10.0
11.0
12.0
13.0
14.0
15.0
16.0
** **務必檢查所有I/O函數的返回值! – user694733
「*但代碼似乎無法從文件中讀取*」您是從什麼結論來的? – alk
顯示您閱讀的文件的第一行。 –