【C】从文件中读取数字

假设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 }

 

posted @ 2015-03-05 15:56  永久指针  阅读(1665)  评论(0编辑  收藏  举报