如何将TXT内容转换为数组啊!!!!
我有一个256*256的矩阵,是TXT格式,用C编程时要将矩阵读入并存入二维数组dist中,以便程序进行,如何实现啊?哪位大哥帮帮小妹吧!![ 本帖最后由 程门映雪 于 2010-4-7 13:36 编辑 ] 使用函数fscanf 本帖最后由 Rainyboy 于 2010-10-18 15:47 编辑
//给你一个我写好的例子
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int row,column;
float **mat;
FILE *fin,*fout;
char *infile,*outfile;
char ifn,ofn;
infile=ifn;
outfile=ofn;
int i,j;
if (argc>3){
printf("You give to many parameters!");
return -1;
}
else if (argc==1){
printf("enter sourse file,please\n");
scanf("%s",infile);
printf("enter a file for result,please\n");
scanf("%s",outfile);
}
else if (argc==2){
infile=argv;
printf("enter a file for result,please\n");
scanf("%s",outfile);
}
else {
infile=argv;
outfile=argv;
}
//输入矩阵的行数和列数
printf("enter the rows of the matrix,please:\n");
scanf("%d",&row);
printf("enter the columns of the matrix,please:\n");
scanf("%d",&column);
if (row!=column){
printf("this is not a squire matrix!");
return -1;
}
//申请空间
mat = (float **)malloc(sizeof(float*)*row);
if (0 == mat){ // 内存申请失败,提示退出
printf("out of memory,press any key to exit...\n");
fprintf(fout,"out of memory,press any key to exit...\n");
exit(0); // 终止程序运行,返回操作系统
}
//申请动态数组列动态申请
for (i=0;i<row;i++)
*(mat+i)=(float *)malloc(sizeof(float)* row);
if ((fin=fopen(infile,"r"))==NULL){ //打开源文件
printf("cannot open infile\n");
exit(0);
}
if ((fout=fopen(outfile,"w"))==NULL){ //打开要保存结果的文件
printf("cannot open outfile\n");
exit(0);
}
//mat从sourse 读取数据
for (i=0;i<row;i++){
for (j=0;j<row;j++)
fscanf(fin,"%f", &mat);
}
//输出读到得矩阵
printf("the origin matrix:\n");
fprintf(fout,"the origin matrix:\n");
for (i=0;i<row;i++){
for (j=0;j<row;j++){
printf("%16f",mat);
fprintf(fout,"%16f", mat);
}
printf("\n");
fprintf(fout,"\n");
}
//养成好习惯
free(mat);
fclose(fin);
fclose(fout);
}
你先试一下吧,不行再说 不明白楼主的意思,
fortran直接open一个文件,再读入到数组中即可的,
或matlab中直接load即可
有甚么困难么
回复 5楼 linqus 的帖子
我记得 FORTRAN 只能读64个字长 好像。。
页:
[1]