方式一:fgetc fputs 实现
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc != 3)
{
fprintf(stderr, "%s <srcfile> <dstfile>\n", argv[0]);
exit(-1);
}
char *srcfile = argv[1];
char *dstfile =argv[2];
FILE *srcfp = fopen(srcfile, "r");
if (NULL == srcfp)
{
perror("can't open srcfile");
exit(-1);
}
FILE *dstfp = fopen(dstfile, "w");
if (NULL == dstfp)
{
perror("can't open or create dstfile");
fclose(srcfp);
exit(-1);
}
char ch;
while ((ch = fgetc(srcfp)) != EOF)
{
fputc(ch, dstfp);
}
fclose(srcfp);
fclose(dstfp);
return 0;
}
方式二:fgets fputs 实现
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
int main(int argc, char **argv)
{
if (argc != 3)
{
fprintf(stderr, "%s <srcfile> <dstfile>\n", argv[0]);
exit(-1);
}
char *srcfile = argv[1];
char *dstfile =argv[2];
FILE *srcfp = fopen(srcfile, "r");
if (NULL == srcfp)
{
perror("can't open srcfile");
exit(-1);
}
FILE *dstfp = fopen(dstfile, "w");
if (NULL == dstfp)
{
perror("can't open or create dstfile");
fclose(srcfp);
exit(-1);
}
char buf[BUFFER_SIZE];
while (fgets(buf, sizeof(buf), srcfp) != NULL)
{
fputs(buf, dstfp);
}
fclose(srcfp);
fclose(dstfp);
return 0;
}
方式三:fread fwrite 实现
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
int main(int argc, char **argv)
{
if (argc != 3)
{
fprintf(stderr, "%s <srcfile> <dstfile>\n", argv[0]);
exit(-1);
}
char *srcfile = argv[1];
char *dstfile =argv[2];
FILE *srcfp = fopen(srcfile, "r");
if (NULL == srcfp)
{
perror("can't open srcfile");
exit(-1);
}
FILE *dstfp = fopen(dstfile, "w");
if (NULL == dstfp)
{
perror("can't open or create dstfile");
fclose(srcfp);
exit(-1);
}
char buf[BUFFER_SIZE];
int ret;
while ((ret = fread(buf, sizeof(char), BUFFER_SIZE, srcfp)) != 0)
{
fwrite(buf, sizeof(char), ret, dstfp);
}
fclose(srcfp);
fclose(dstfp);
return 0;
}
方式四:read write 实现
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFER_SIZE 1024
ssize_t mywrite(int fd, const void *buf, size_t count);
ssize_t mywrite(int fd, const void *buf, size_t count)
{
int ret;
int num_written = 0;
while(1)
{
ret = write(fd, buf + num_written, count);
if (ret == -1)
{
return -1;
}
else if (ret == count)
{
return num_written + ret;
}
num_written += ret;
count -= ret;
}
}
int main(int argc, char **argv)
{
if (argc != 3)
{
fprintf(stderr, "%s <srcfile> <dstfile>\n", argv[0]);
exit(-1);
}
char *srcfile = argv[1];
char *dstfile =argv[2];
int srcfd = open(srcfile, O_RDONLY);
if (-1 == srcfd)
{
perror("can't open srcfile");
exit(-1);
}
int dstfd = open(dstfile, O_WRONLY | O_CREAT, 0644);
if (-1 == dstfd)
{
perror("can't open or create dstfile");
close(srcfd);
exit(-1);
}
char buf[BUFFER_SIZE];
int ret;
while (1)
{
ret = read(srcfd, buf, sizeof(buf));
if (ret == -1)
{
return -1;
}
else if (ret == 0)
{
break;
}
ret = mywrite(dstfd, buf, ret);
}
close(srcfd);
close(dstfd);
return 0;
}