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

 

你可能感兴趣的:(文件操作)