通过系统调用实现 file.copy
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(
int argc,
char *argv[])
{
if (argc !=
3)
{
printf(
"usage : ./copy filename1 filename2\n");
}
char buffer[
1024] = {
0};
int fd1 = open(argv[
1], O_RDWR);
if (-
1 == fd1)
{
perror(
"open1");
return 1;
}
int fd2 = open(argv[
2], O_RDWR | O_CREAT, S_IRWXU);
if (-
1 == fd2)
{
perror(
"open2");
return 2;
}
int count =
0;
while (count = read(fd1, buffer,
1024))
{
if (-
1 == count)
{
perror(
"read1");
close(fd1);
close(fd2);
return 3;
}
int coun2 = write(fd2, buffer, count);
if (-
1 == count)
{
perror(
"write1");
close(fd1);
close(fd2);
return 4;
}
memset(buffer,
0,
1024);
}
close(fd1);
close(fd2);
return 0;
}
通过库函数实现 file.copy
#include <stdio.h>
#include <string.h>
int main(
int argc,
char *argv[])
{
if (argc !=
3)
{
printf(
"usage : ./copy filename1 filename2\n");
}
char buffer[
1024] = {
0};
FILE *file1 = fopen(argv[
1],
"r+");
if (NULL == file1)
{
perror(
"fopen");
return 1;
}
FILE *file2 = fopen(argv[
2],
"w+");
if (NULL == file2)
{
perror(
"fopen");
return 2;
}
int count =
0;
count = fread(buffer,
sizeof(
char),
1024, file1);
if(
0 == count)
{
perror(
"fread");
fclose(file1);
fclose(file2);
return 3;
}
fseek(file1,
0, SEEK_SET);
while (count = fread(buffer,
sizeof(
char),
1024, file1))
{
int count2 = fwrite(buffer,
sizeof(
char), count, file2);
if (count2 ==
0)
{
perror(
"fwrite");
fclose(file2);
fclose(file1);
return 4;
}
memset(buffer,
0,
1024);
}
fclose(file1);
fclose(file2);
return 0;
}