C 练习(五)文件操作

#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() 方式处理文件

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值