</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>
文件读写操作
最新推荐文章于 2022-11-14 23:27:40 发布