åèæè·¯ï¼
æå¼æ件ï¼ç¶å读å
¥ä¸è¡å°å符串stréé¢ï¼å¾ªç¯è¯»åè¡å³å¯ï¼
åèä¾åå¦ä¸ï¼
#include <stdio.h>
#include <stdlib.h>
/*
1.txt
1,2,3,4,5,6,7
8,9,10,11,12,13,14
15,16,17,18,19,20,21
*/
int main ()
{
FILE *fp;
int **a;//å®ä¹äºç»´æ°ç»
int i,j;
int row=0,column=0;//è¡ï¼å
char ch;
//æå¼æ件
if((fp=fopen("1.txt","r"))==NULL)
{
printf("open error\n");
return 1;
}
//ç»è®¡åæ°
while(!feof(fp)&&(ch=fgetc(fp))!='\n')
if(ch==',')
column++;
column++;
if(column==1)
{
printf("no data\n");
return 1;
}
//ç½®æ件é¦é¨
fseek(fp,0L,0);
//ç»è®¡è¡æ°
while(!feof(fp))
if(fgetc(fp)=='\n')
row++;
row++;
if(row==1)
{
printf("no data\n");
return 1;
}
//å¼è¾å
å
a=(int**)malloc(sizeof(int*)*row);
if(a==NULL)
{
printf("no memory\n");
return 1;
}
for(i=0;i<row;i++)
{
a[i]=(int*)malloc(sizeof(int)*column);
if(a[i]==NULL)
{
printf("no memory\n");
return 1;
}
}
//ç½®æ件é¦é¨
fseek(fp,0L,0);
//读å
¥æ°æ®
while(!feof(fp))
for(i=0;i<row;i++)
for(j=0;j<column;j++)
fscanf(fp,"%d,",&a[i][j]);
//è¾åºæ¾ç¤º
for(i=0;i<row;i++)
{
for(j=0;j<column;j++)
j==column-1?printf("%d",a[i][j]):printf("%d,",a[i][j]);
printf("\n");
}
//å
³éæ件
fclose(fp);
//éæ¾å
å
for(i=0;i<row;i++)
free(a[i]);
free(a);
return 0;
}
温馨提示:答案为网友推荐,仅供参考