文件复制
#include <stdio.h>
int copyFile(const char *srcfile,const char *destfile){
FILE *fpsrc = fopen(srcfile,"r");
if(fpsrc == NULL){
//access函数可以判断一个文件是否存在
printf("fopen %s failed!\n",srcfile);
return -1;
}
FILE *fpdest = fopen(destfile,"w");
if(fpdest == NULL){
printf("fopen %s failed!\n",destfile);
fclose(fpsrc);
return -1;
}
int ch = 0;
while((ch = fgetc(fpsrc))!=EOF){//读取文件末尾返回-1
//putchar(ch);
fputc(ch,fpdest);
}
fclose(fpsrc);
fclose(fpdest);
}
//a.out src.txt dest.txt
int main(int argc,char *argv[]){
if(argc < 3){
printf("%s srcfilename destfilename\n",argv[0]);
return -1;
}
copyFile(argv[1],argv[2]);
return 0;
}
文件长度
#include <stdio.h>
long filesize(const char *file){
FILE *fp = fopen(file,"r+");
if(fp == NULL){
return -1;
}
fseek(fp,0,SEEK_END);
long off = ftell(fp);
fclose(fp);
return off;
}
int main(int argc,char *argv[]){
if(argc < 2){
printf("use : %s file\n",argv[0]);
return -1;
}
long size = filesize(argv[1]);
printf("%ld\n",size);
return 0;
}
文件加密
#include <stdio.h>
int encode(const char *file){
FILE *fp = fopen(file,"r+");
if(fp == NULL){
printf("fopen %s failed!\n",file);
return -1;
}
char c = 0;
while(fread(&c,1,1,fp)>0){
c = ~c;
fseek(fp,-1,SEEK_CUR);
fwrite(&c,1,1,fp);
}
fclose(fp);
}
int main(int argc,char *argv[]){
if(argc < 2){
printf("use: %s file\n",argv[0]);
return -1;
}
encode(argv[1]);
return 0;
}