C语言文件读写 C语言实现文件读写操作

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C语言文件读写 C语言实现文件读写操作

零商   2021-01-28 我要评论

键盘读入字符串写到文件中,再从文件读出显示在控制台

#include<stdio.h>
#include<string.h>
int main()
{
 FILE *fp;
 char string[6];//方括号中是几就输入几个字符串
 if( (fp=fopen("file.txt","w"))==NULL )
 {
 printf("cannot open file");
 return 0;
 }
 while(strlen(gets(string)) > 0)
 {
 fputs(string,fp);
 fputs("\n",fp);
 }
 fclose(fp);

 if( (fp=fopen("file.txt","r"))==NULL)
 {
 printf("cannot open file\n");
 return 0;
 }
 while(fgets(string,6,fp)!=NULL)
 {
 fputs(string,stdout);//系统自动打开stdout文件
 }
 fclose(fp);
}

合并两个文件的内容,并输出到第三个文件

#include<stdio.h>
#include<string.h>
int main()
{
 FILE *fp1,*fp2,*fp3;
 char str1[10],str2[10];
 printf("输入两串字母\n");
 scanf("%s",str1);
 scanf("%s",str2);
 
 //A,B两个文件赋值
 if((fp1=fopen("A.txt","w"))==NULL)
 {
 printf("cannot open file\n");
 return 0;
 } 
 fputs(str1,fp1); 
 fclose(fp1);

 if((fp2=fopen("B.txt","w"))==NULL)
 {
 printf("cannot open file\n");
 return 0;
 } 
 fputs(str2,fp2); 
 fclose(fp2);
 
 //拷贝到第三个文件
 if((fp1=fopen("A.txt","r"))==NULL)
 {
 printf("cannot open file\n");
 return 0;
 }
 if((fp2=fopen("B.txt","r"))==NULL)
 {
 printf("cannot open file\n");
 return 0;
 }
 if((fp3=fopen("C.txt","a"))==NULL)
 {
 printf("cannot open file\n");
 return 0;
 }
 while(!feof(fp1))
 {
 fputc(fgetc(fp1),fp3);
 }
 while(!feof(fp2))
 {
 fputc(fgetc(fp2),fp3);
 }
 fclose(fp1);
 fclose(fp2);
 fclose(fp3);
}

输入学生信息并转存到磁盘文件

#include<stdio.h>
#define SIZE 4
struct student_type
{
 char name[10];
 int num;
 int age;
 char addr[15];
};
struct student_type stud[SIZE];

void save();
void display();
void main()
{
 int i;
 for(i=0;i<SIZE;i++)
 {
 scanf("%s %d %d %s",stud[i].name, &stud[i].num, &stud[i].age, stud[i].addr);
 }

 save();//转存
 display();
}

void save()
{
 FILE *fp;
 int i;
 if((fp=fopen("E:\\计算机导论作业\\加密文档","wb"))==NULL)
 {
 printf("cannot open file\n");
 return;
 }
 for(i=0;i<SIZE;i++)
 {
 if(fwrite(&stud[i], sizeof(struct student_type),1,fp)!=1)
  printf("file write error\n");
 }
 fclose(fp);
}

void display()
{
 FILE *fp;
 int i;
 if((fp=fopen("E:\\计算机导论作业\\加密文档","rb"))==NULL)
 {
 printf("cannot open file\n");
 return;
 }
 for(i=0;i<SIZE;i++)
 {
 fread(&stud[i], sizeof(struct student_type), 1, fp);
 printf("%-10s %4d %4d %-15s\n",stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
 }
 fclose(fp);
}

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们