c语言写入文件用哪个字母,C语言实现文件读写操作

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

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

#include

#include

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

#include

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

#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

{

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

{

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

{

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

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值