Linux系统编程
文件拷贝
代码位置:D:\Linux\myClass\cpfile
0.创建一个文件夹cpfile
1.编写main.c函数,存放于cpfile中
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
// argv[0] argv[1] argv[2]
// ./mucp srcfile dstfile
// 实现将文件srcfile拷贝为文件dstfile
// srcfile为源文件 dstfile为要新建的文件
int main(int argc, char *argv[])
{
// 定义一个缓冲区
char buf[512]={0};
int fd_src, fd_dst;
// 打开源文件只读形式
fd_src = open(argv[1], O_RDONLY);
if (fd_src == -1)
{
perror("open src error");
return -1;
}
// 创建新建的文件为只写方式
fd_dst = open(argv[2], O_WRONLY | O_CREAT, 0755);
if (fd_dst == -1)
{
perror("open dst error");
return -1;
}
// 拷贝文件的过程
int count;
while (1)
{
count = read(fd_src, buf, 512);
if(count==0){
break;
}
write(fd_dst,buf,count);
memset(buf,0,512);
}
close(fd_src);
close(fd_dst);
}
2.编译main.c,编译后的结果为main
gcc -o main main.c
3.在cpfile夹下创建一个文件test.txt
4.执行main
// 原文件 目标文件
./main test.txt newtest.txt
求文件内容的长度
代码位置:D:\Linux\myClass\filesize
0.创建一个文件夹filesize
1.编写main.c函数,存放于filesize中
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
// argv[0] argv[1]
// ./filesize filename
// 实现获取filename文件的大小(以字节为单位)
int main(int argc, char *argv[])
{
int fd_src;
// 打开源文件只读形式
fd_src = open(argv[1], O_RDONLY);
if (fd_src == -1)
{
perror("open src error");
return -1;
}
long int size;
size=lseek(fd_src,0,SEEK_END);
printf("%s size:%ld\n",argv[1],size);
close(fd_src);
}
2.编译mian.c,编译后的结果为main
gcc -o main main.c
3.在cpfile夹下创建一个文件test.txt,并写入内容
4.执行main
// 文件名
./main test.txt