C 練習(五)檔案操作

來源:互聯網
上載者:User
#include "stdio.h"#include "stdlib.h"void main(){        FILE *fp1 ,*fp2;    char c;    if((fp1 = fopen("test.txt","w")) == NULL){       printf("can't create the file");    }    while((c = getchar()) != '\n')         fputc(c,fp1);         fclose(fp1);         if( (fp2 = fopen("test.txt","r")) == NULL ){           printf("無法開啟檔案");           exit(0);         }         printf("輸出字元\n");         while( (c=fgetc(fp2)) != EOF){             putchar(c);         }         printf("\n");         fclose(fp2);}

//檔案工作字元讀寫

#include "stdio.h"#include "string.h"#include "stdlib.h"void main(){        FILE *fp1 ,*fp2;    char str[10];    if((fp1 = fopen("test.txt","w")) == NULL){       printf("無法開啟該檔案");    }    puts("請輸入字元");    gets(str);    while(strlen(str)>0){       fputs(str,fp1);       fputs("\n",fp1);       gets(str);    }    fclose(fp1);    if((fp2 = fopen("test.txt","r")) == NULL){       printf("無法開啟檔案");    }    printf("輸出該字元");    while(fgets(str,10,fp2)!= NULL)        printf("輸入字元為:%s",str);    printf("\n");    fclose(fp2);}

字串輸入輸出

 

#include "stdio.h"#include "string.h"#include "stdlib.h"void main(){        FILE *fp1;    int i,score1[4],score2;    char name1[4][8],name2[10];    if(( fp1 = fopen("text.txt","w")) == NULL){         printf("無法讀取");    }    puts("輸入姓名、成績");    for(i =0;i<4;i++){      scanf("%s %d",&name1[i],&score1[i]);      fprintf(fp1,"%s %d\n",name1[i],score1[i]);    }    fclose(fp1);    if( (fp1 = fopen("text.txt","r")) == NULL){        printf("無法開啟");        exit(0);    }    printf("輸入資料\n");    while(!feof(fp1)){       fscanf(fp1,"%s %d\n",name2,&score2);       printf("姓名為%s 成績為%d\n",name2,score2);    }    fclose(fp1);    }

fprintf(); / fscanf() 方式處理檔案

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.