【C】從檔案中讀取數字

來源:互聯網
上載者:User

標籤:

假設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】從檔案中讀取數字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.