fgets+fputc
#include<stdio.h>
int main(int argc,char *argv[])
{
if(argc<3)
{
printf("usage: ./a.out srcfile destfile");
return 1;
}
FILE *src = fopen(argv[1],"r");
FILE *dest = fopen(argv[2],"w");
if(NULL == src || NULL == dest)
{
perror("fopen");
return 1;
}
while(1)
{
int c = fgetc(src);
if(EOF == c)
{
break;
}
fputc(c,dest);
}
fclose(dest);
fclose(src);
return 0;
}
用到的函数:
FILE *fopen(const char *pathname, const char *mode);
int fgetc(FILE *stream);
int fputc(int c, FILE *stream);
int fclose(FILE *stream);
fgets+fputs
#include<stdio.h >
int main(int argc,char *argv[])
{
if(argc<3)
{
printf("usage: ./a.out srcfile destfile");
return 1;
}
FILE * src_fp = fopen(argv[1],"r");
FILE * dest_fp = fopen(argv[2],"w");
if(NULL == src_fp || NULL == dest_fp)
{
perror("fopen");
return 1;
}
char buf[1024] = {0};
while(1)
{
char *s = fgets(buf,sizeof(buf),src_fp);
if(NULL == s)
{
break;
}
fputs(buf,dest_fp);
}
fclose(dest_fp);
fclose(src_fp);
return 0;
}
用到的函数:
FILE *fopen(const char *pathname, const char *mode);
char *fgets(char *s, int size, FILE *stream);
int fputs(const char *s, FILE *stream);
int fclose(FILE *stream);
fread+fwrite
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc,char*grav[])
{
FILE * src_fp = fopen(argv[1],"r");
FILE * dest_fp = fopen(argv[2],"w");
if(NULL == src_fp || NULL == dest_fp)
{
perror(fopen);
return 1;
}
int size = 1024*1024;//size of srcfile(argv[1])
char *p = (char*)malloc(size);
fread(p,size,1,src_fp);
fwrite(p,size,1,dest_fp);
fclose(dest_fp);
fclose(src_fp);
free(p);
return 0;
}
用到的函数:
FILE *fopen(const char *pathname, const char *mode);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
int fclose(FILE *stream);
read+write
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
int main(int argc,char *srgv[])
{
if(argc<3)
{
fprintf(stderr,"usage: ./a.out srcfile deatfile\n");
return 1;
}
int src_fd = open(argv[1],O_RDONLY);
int dest_fd = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0666);
if(-1 == src_fd || -1 == dest_fd)
{
perror("open");
return 1;
}
while(1)
{
char[512] = {0};
int rd_ret = read(src_fd,buf,sizeof(buf));
if(rd_ret<=0)
{
break;
}
write(dest_fd,buf,rd_ret);
}
close(dest_fd);
close(src_fd);
return 0;
}
用到的函数:
int open(const char *pathname, int flags, mode_t mode);
int fprintf(FILE *stream, const char *format, ...);
void perror(const char *s);
ssize_t read(int fd, void *buf, size_t count);ssize_t write(int fd, const void *buf, size_t count);
int close(int fd);