文件读写操作

</pre><p><span style="font-size:18px;">文件的读写操作,fread和fwrite是二进制文件的操作,也可以通过它们你对文件进行加密。</span></p><p><span style="font-size:14px;">#include <stdio.h>#include <stdlib.h>#include <error.h>#include <string.h>struct work{    int number;    char name[20];    int age;};struct stu{    char name[10];    int age;};int main01(void){    struct stu mystu[3];    FILE *p;    extern int errno;    char file[] = "F:\\b.txt";    int i;    strcpy(mystu[0].name,"jim");    mystu[0].age = 15;    strcpy(mystu[1].name,"tom");    mystu[1].age = 12;    strcpy(mystu[2].name,"jam");    mystu[2].age = 16;    p = fopen(file,"w");    if(p == NULL)    {        printf("can't open file %s\n",file);        //printf("error:%d\n",error);        return 0;    }    else        printf("%s was opened \n",file);    i = fwrite(mystu,sizeof(mystu),3,p);    printf("%d bit was written\n",i);    close(p);    return 0;}int main02(){    FILE *p = fopen("F:\\d.txt","wb");    int i = 97;    fwrite(&i,sizeof(int),1,p);    fclose(p);    return 0;}int main(){    struct work wk;    FILE *p1 = fopen("F:\\a.txt","rb");    FILE *p2 = fopen("F:\\b.txt","wb");    if(p1 == NULL)        return 0;    if(p2 == NULL)        return 0;    while(!feof(p1))    {        fread(&wk,sizeof(struct work),1, p1);        fwrite(&wk,sizeof(struct work),1,p2);    }    fclose(p1);    fclose(p2);    return 0;}</span></p><h2>文件加密代码</h2><div><pre name="code" class="cpp"><span style="font-family:FangSong_GB2312;font-size:18px;">#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define MAX 1024 * 1024 * 256
//动态给数组分配内存

int main01()
{
	FILE *p1 = fopen("F:\\b.txt","rb");
	FILE *p2 = fopen("F:\\c.txt", "wb");
	struct stat st = { 0 };
	long size1 = 0;
	if (st.st_size <= MAX)
		size1 = st.st_size;
	else
		size1 = MAX;
	char *buf = calloc(size1, 1);
	//char buf[1024] = { 0 };
	while (!feof(p1))
	{
		int rc = fread(buf, 1, sizeof(buf), p1);
		fwrite(buf, rc, 1, p2);
	}
	printf("%s",buf);
	getchar();
	return 0;
}

int main()
{
	FILE *p = fopen("F:\\b.txt","r");
	long size1 = 0;
	struct stat st = { 0 };
	if (st.st_size <= MAX)
		size1 = st.st_size;
	else
		size1 = MAX;
	char *buf = calloc(size1,1);
	while (1)
	{
		char tmp[1024] = { 0 };
		if (fgets(tmp, sizeof(tmp), p) == NULL)
		{
			break;
		}
		strcat(buf, tmp);
	}
	fclose(p);
	return 0;
		
}</span>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值