llinux文件编程2
来源:互联网 发布:unity3d awake 编辑:程序博客网 时间:2024/05/18 16:39
本文通过一个拷贝文件的程序介绍下,linux访问系统库函数open close read write四个函数
1.先把完整程序贴上,在一步一步介绍程序流程。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define size 1000
int bytes_read,bytes_write;
char buf[size];
int main(int argc,char *argv[])
{
int fd1,fd2;
char *p;
if(argc!=3)
{
printf("input format mistake: only and but only two file name \n");
exit(1);
}
if((fd1=open(argv[1],O_RDONLY))<0)
{
printf("open file1 failed!\n");
exit(1);
}
if((fd2=open(argv[2],O_WRONLY|O_CREAT,0755))<0)
{
printf("open file2 failed!\n");
exit(1);
}
while(bytes_read=read(fd1,buf,size))
{
if(bytes_read<0)
break;
else if(bytes_read>0)
{
p=buf;
while(bytes_write=write(fd2,p,bytes_read))
{
if((bytes_write<0)||(bytes_write==bytes_read))
break;
else if((bytes_write>0)&&(bytes_write!=bytes_read))
{
p+=bytes_write;
bytes_read=bytes_read-bytes_write;
}
}
}
}
close(fd1);
close(fd2);
}
2:程序分析
2.1 首先进行参数检查,总共三个参数,两个文件,把一个文件的数据的一部分拷贝到另一个文件中
if(argc!=3)
{
printf("input format mistake: only and but only two file name \n");
exit(1);
}
2.2 建立总体框架
打开两个文件,一个文件只读就可以了,另一个设置为可写,当不存在时,必须要创建,同时可以先把关闭文件
的函数先写了。
if((fd1=open(argv[1],O_RDONLY))<0)
{
printf("open file1 failed!\n");
exit(1);
}
if((fd2=open(argv[2],O_WRONLY|O_CREAT,0755))<0)
{
printf("open file2 failed!\n");
exit(1);
}
.....
close(fd1);
close(fd2);
3.打开文件成功后,开始进入拷贝文件过程
1.bytes_read=read(fd1,buf,size);读取size个字节,实际读到多少,返回为bytes_read
2.此时继续进行判断,当返回值bytes_read<0,代表没有读到东西,直接退出循坏,此时没有必要拷贝
若读到内容,则开始把读出来的内容放到另一个文件中。
3.else if(bytes_read>0)
{
p=buf;
while(bytes_write=write(fd2,p,bytes_read))
{
if((bytes_write<0)||(bytes_write==bytes_read))
break;
else if((bytes_write>0)&&(bytes_write!=bytes_read))
{
p+=bytes_write;
bytes_read=bytes_read-bytes_write;
}
}
这里为什么要设置一个指针指向buf数组,为什么还要用while循环呢?
因为:bytes_write=write(fd2,p,bytes_read) 调用这个函数时,虽然要求写入bytes_read个字节
但实际的情况可能一次性不能写入这么多字节,因此通过返回值bytes_write就可以知道究竟写入多少字节
当bytes_write<0直接退出,写入失败,或bytes_write=bytes_read 写入成功,也退出。
(bytes_write>0)&&(bytes_write!=bytes_read)一次性没写完,继续把剩余的写完。
- llinux文件编程2
- lLinux编程大全
- Llinux下查到文件
- llinux 文件搜索命令
- Llinux常用命令2
- llinux(-)
- Llinux SCP 远程拷贝文件
- llinux ls 统计文件个数
- Llinux实验——SHELL编程
- llinux的shell脚本编程详解
- llinux 网络配置和oracle 几个文件
- llinux根文件系统/etc/passwd文件详解
- llinux根文件系统/etc/passwd文件详解
- Linux基础之文件权限LLinux
- llinux根文件系统/etc/passwd文件详解
- llinux 下查看文件个数及大小
- lLinux设备驱动子系统- SD卡(2)
- lLinux设备驱动子系统- SD卡(2)
- Windows10 和 Ubuntu 16.04 双系统 系统时间不统一解决
- 关于开发工具不能找到系统中已经存在的字体
- swift 基础学习回顾(一)
- 【Leetcode】200. Number of Island
- NYOJ 255
- llinux文件编程2
- mt4
- JavaScript 深拷贝 & 浅拷贝
- [读书笔记]python爬虫-scrapy安装过程常见问题及解决方法
- Mac文件系统
- 缓存淘汰算法之LRU
- Unity常用插件之DoTween(一)
- 学习贵在坚持!
- [python]python常用内置函数