对文件操作有两种方式:
A、系统调用方式,这个是基于具体的操作系统
B、调用C库函数方式
下面具体讲解这两种方式,以及用到的相关的函数;
A:系统调用(系统函数Linux为例)
综合实例,用系统函数编程实现文件的拷贝:
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #define MAX_SIZE 1024
- void copy(char *from_file,char *to_file)
- {
- int from_fd ;
- int to_fd;
- char buff[MAX_SIZE];
- int read_size;
- int write_size;
- if((from_fd = open(from_file,O_RDONLY))==-1)
- {
- printf("The file of %s don't exist!\n",from_file);
- exit(1);
- }
- if((to_fd=open(to_file,O_WRONLY|O_CREAT,0777))==-1)
- {
- printf("The file of %s don't exist!\n",to_file);
- exit(1);
- }
- while((read_size=read(from_fd,buff,MAX_SIZE))>0)
- {
- write_size = write(to_fd,buff,read_size);
- while(write_size<read_size)
- {
- read_size -= write_size;
- write_size += write(to_fd,buff,read_size);
- }
- }
- close(from_fd);
- close(to_fd);
- }
- int main(int argc, char *argv[])
- {
- int i;
- char *from_file;
- char *to_file;
- if(argc!=3){
- printf("Please input a right expression\n");
- exit(1);
- }else{
- from_file = argv[1];
- to_file = argv[2];
- copy(from_file,to_file);
- }
- return 0;
- }
B,用C库函数编程实现文件的拷贝
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAX_SIZE 1024
- void copy(FILE *form_file,FILE *to_file);
- int main(int argc,char *argv[])
- {
- FILE *from_file;
- FILE *to_file;
- if(argc!=3){
- printf("Please input a right expression!\n");
- exit(1);
- }else{
- if((from_file=fopen(argv[1],"rb"))==NULL)
- {
- printf("Can't open the file of %s\n",argv[1]);
- exit(1);
- }
- if((to_file=fopen(argv[2],"wb"))==NULL)
- {
- printf("Can't open the file of %s!\n",argv[2]);
- exit(1);
- }
- copy(from_file,to_file);
- }
- return 0;
- }
- void copy(FILE *from_file,FILE *to_file)
- {
- char buff[MAX_SIZE];
- long file_size;
- fseek(from_file,0L,SEEK_END);
- file_size = ftell(from_file);
- fseek(from_file,0L,SEEK_SET);
- // printf("The file size is:%d\n",file_size);
- while(!feof(from_file))
- {
- memset(buff,0,MAX_SIZE);
- fread(buff,MAX_SIZE,1,from_file);
- if(file_size<MAX_SIZE){
- fwrite(buff,file_size,1,to_file);
- }else{
- fwrite(buff,MAX_SIZE,1,to_file);
- file_size -= MAX_SIZE;
- }
- }
- fclose(from_file);
- fclose(to_file);
- }
相关资料链接:http://www.educity.cn/linux/1241676.html
http://www.cnblogs.com/TianFang/archive/2013/01/22/2870663.html
http://wenku.baidu.com/link?url=l6Y04y286Fs7YlgGAHBSGhqnz-2VdZ0-KWQhLEklcYwyhAu4oAtZXS0npqeovSrnKMEiE22w_k0-HSFmCIM4aH8bmHTf0o7fn9BrvjMRCRm