#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() 方式處理檔案