C格式化讀取txt檔案內容
阿新 • • 發佈:2019-02-11
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> struct localtion{ unsigned int lx; unsigned int ly; unsigned int rx; unsigned int ry; //char * textinfo; }; int formatreadtxt(char *filename) { FILE*fp; int num[10],j=0; char line[50]; char ch; int line_num=1; struct localtion textarea={0}; if ((fp=fopen(filename,"r"))==NULL) { printf("讀取檔案失敗!"); return -1; } while(fgets(line,50,fp)!=NULL) { char temp[4]=" "; printf("第%d行:",line_num++); fputs(line,stdout); unsigned int label=0; for (int i=0;i<strlen(line);i++) { ch=line[i]; if (isdigit(ch)) { //將數字字元拼接,依次存入temp的前4個字元裡 temp[j++]=ch; } else if (ch==',') { j=0; label++; switch(label) { case 1: textarea.lx=atoi(temp); printf("lx:%d\n",textarea.lx); memset(temp, '\0', sizeof(temp)); break; case 2: textarea.ly=atoi(temp); printf("ly:%d\n",textarea.ly); memset(temp, '\0', sizeof(temp)); break; case 3: textarea.rx=atoi(temp); printf("rx:%d\n",textarea.rx); memset(temp, '\0', sizeof(temp)); break; case 4: textarea.ry=atoi(temp); printf("ry:%d\n",textarea.ry); memset(temp, '\0', sizeof(temp)); break; default: break; } } } } //for (i=0;i<10;i++) //{ // fscanf(fp,"%d",&num[i]);//讀入9個數據 //} //for(i=0;i<10;i++) //{ // printf("%d ",num[i]);//顯示9個數據 //} fclose(fp); getchar(); return 0; }