C语言实现文件读写操作

本文实例为大家分享了C语言实现文件读写操作的具体代码,供大家参考,具体内容如下

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

#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);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。