C语言——文件操作
1.文件拷贝
#include
int main(int argc,char** argv)
{
FILE *src=NULL;
FILE *new=NULL;
int n_read=0;
unsigned char buf[1024]={0};
src=fopen("./file","r+");
if(src==NULL)
{
printf("文件打开失败\n");
return -1;
}
new=fopen("./file1","w+");
if(new==NULL)
{
printf("文件打开失败\n");
return -1;
}
while(!feof(src))
{
n_read=fread(buf,1,sizeof(buf),src);
fwrite(buf,1,n_read,new);
}
fclose(src);
fclose(new);
printf("文件拷贝成功\n");
return 0;
}
2.文件加解密实现
2.1.实现方式一:
#include
void eneryFile(char* file1,char* file2,int key)
{
FILE* fp1=fopen(file1,"r+");
FILE* fp2=fopen(file2,"w+");
int data=0;
int n_read=0;
while(!feof(fp1))
{
n_read=fread(&data,1,sizeof(int),fp1);
data=data^key;
fwrite(&data,1,n_read,fp2);
}
fclose(fp1);
fclose(fp2);
}
void deneryFile(char* file1,char* file2,int key)
{
eneryFile(file1,file2,key);
}
void printListInfo()
{
printf("\n--------------菜单----------------\n");
printf("1. 加密\n");
printf("2. 解密\n");
printf("请选择功能序号:");
}
int main(int argc,char** argv)
{
char* src_file="./file";
char* new_file="./file1";
char* new2_file="./file2";
int key=123;
int number=0;
while(1)
{
printListInfo();
scanf("%d",&number);
switch(number)
{
case 1:
eneryFile(src_file,new_file,key);
break;
case 2:
deneryFile(new_file,new2_file,key);
break;
default:
printf("输入错误\n");
break;
}
}
return 0;
}
3.fread
#include
#include
#include
int main(int argc,char** argv)
{
FILE* file=NULL;
int ret=0;
char buf[100]={0};
file=fopen("./text","r+");
if(file==NULL)
{
printf("open file failed\n");
return -1;
}
ret=fread(buf,1,sizeof(buf),file);
if(ret!=-1)
{
printf("read file success\n");
printf("buf=%s\n",buf);
return -1;
}
fclose(file);
return 0;
}
4.fwrite
#include
#include
int main(int argc,char** argv)
{
int i=0;
for(i=0;i<argc;i++)
{
printf("argc[%d]=%s\n",i,argv[i]);
}
FILE *file=NULL;
char *buf="xiewenhui";
int ret=0;
file=fopen("./text","w+");
if(file==NULL)
{
printf("open file error\n");
return -1;
}
ret=fwrite(buf,1,strlen(buf),file);
if(ret==-1)
{
printf("write failed\n");
return -1;
}
fclose(file);
return 0;
}
5.写入结构体到链表
void saveLink(Node* head)
{
FILE *fp=NULL;
Node* p=head;
Node* new=(Node*)malloc(sizeof(Node));
new->next=NULL;
fp=fopen("./text.txt","w+");
if(fp==NULL)
{
printf("file open failed\n");
return;
}
while(p->next!=NULL)
{
fwrite(p,sizeof(Node),1,fp);
p=p->next;
}
fclose(fp);
}
6.写入数据到结构体
#include
typedef struct Test
{
int a;
int b;
char c[100];
}Demo;
int main(int argc,char **argv)
{
Demo stu={888,666,"xie"};
FILE *file=NULL;
int ret=0;
file=fopen("./text","w+");
if(file==NULL)
{
printf("文件打开失败\n");
return -1;
}
ret=fwrite(&stu,sizeof(Demo),1,file);
if(ret==1)
{
printf("写入成功:%d\n",ret);
return -1;
}
fclose(file);
return 0;
}
7.从结构体中读取数据