標籤:
假設src.txt是包含各種ascii字元的文字檔。請提取src.txt文本中的數字,並儲存在dst.txt檔案中。數字之間用空格隔開。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #define IN 0 6 #define OUT 1 7 8 /*從名為src檔案中找到數字,將其寫入到名字為dst的檔案中*/ 9 int write_digit(char *dst, char *src)10 {11 FILE *fp1;12 FILE *fp2;13 if( !(fp1 = fopen(src,"r")))14 {15 fprintf(stderr,"failed to open %s\n",src);16 exit(-1);17 }18 if( !(fp2 = fopen(dst,"w+")))19 {20 fprintf(stderr,"failed to open %s\n",dst);21 exit(-1);22 }23 int ch;24 int state = OUT;25 while( (ch = fgetc(fp1))!=EOF)26 {27 if( ch < ‘0‘ || ch > ‘9‘)28 {29 if(IN == state)30 {31 fputc(‘ ‘,fp2);32 }33 state = OUT;34 }35 else 36 {37 fputc(ch,fp2);38 state = IN;39 }40 }41 fclose(fp1);42 fclose(fp2);43 return 0;44 }45 46 int main()47 {48 char *s1 = "src.txt";49 char *s2 = "dst.txt";50 write_digit(s2, s1);51 return 0; 52 }
【C】從檔案中讀取數字