Linux_C之文件操作

来源:互联网 发布:qq农场刷经验软件 编辑:程序博客网 时间:2024/05/24 05:05

Linux_C之文件操作

分类: linux 217人阅读 评论(0) 收藏 举报
wite系统调用:
系统调用write的作用是,把缓冲区buf的前nbytes个字节写入与文件描述fildes关联的文件中。它的返回实际写入的字节数,如果文件描述符有错或者底层的设置驱动程序对数据快长度比较敏感,该返回值可能会小于nbytes。如果这个函数的返回值为0,就表示未写出任何数据。如果是-1,就表示在write条用中出现了错误,对应的错误代码保存在全局变量errno里面。
#include <unistd.h>
size_t write(int fildes,const void *buf,size_t nbytes);
read系统调用:
系统调用read的作用是从与文件描述符fildes相关联的文件理读入nbytes个字节的数据,并把它们放入数据区buf中。它返回实际读入的字节数。它可能小于请求的字节数。如果read调用返回0,就表示未读过任何数据,已经达了文件尾,如果是-1,就表示read调用出现了错误。
#include <unistd.h>
size_t read(int fildes,void *buf,size_t nbytes);
open系统调用:
#include <fcntl.h>
#include <sys/type.h>
#include <sys/stat.h>

int open(const char *path,int oflags);
int open(const char *path,int oflags,mode_t mode);
open建立一条到文件或设备的访问路径。准备打开的文件或设备的名字作为参数path传递给函数,oflags参数用来定义打开文件所采取的动作。

模式:  O_RDONLY   以只读方式打开
       O_WRONLY   以只写方式打开
       O_RDWR     以读写方式打开
open调用还可以在oflags参数中包括下列可选模式的组合(用“按位或”操作);
O_APPEND: 把写入数据追加在文件的未尾
O_TRUNC :把文件的长度设置为零,丢弃已有的内容
O_CREAT: 如果需要,就按参数mode中给出的访问模式创建文件
O_EXCL:与O_CREAT一起使用,确保调用者创建出文件。
mode模式:
S_IRUSR: 读权限,文件属主
S_IWUSR: 写权限,文件属主
S_IXUSR: 执行权限,文件属主
S_IRGRP: 读权限,文件所属组
S_IWGRP: 写权限,文件所属组
S_IXGRP: 执行权限,文件所属组
S_IROTH: 读权限,其他用户
S_IWOTH: 写权限,其他用户
S_IXOTH: 执行权限,其他用户
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main(){
  char c;
  int in,out;

  in=open("file.in",O_RDONLY);
  out=open("file.out",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);
  while(read(in,&c,1) == 1)
    write(out,&c,1);

  exit(0);
}

$ TIMEFORMAT="" time copy_system//linux下测试时间命令
4.76user 146.90system 2:32.57elapsed 99%CPU

$ls -ls file.in file.out
1092 -rw-r-r- 1 neil users    1048576 sep 17 10:46 file.in
1092 -rw-----  1 neil users  1048576 sep 17 10:51 file.out
这个代码花费了大约两分半钟,并且消耗了所有的CPU时间,之所以那么慢,是应为它必须网城超过两百万次的系统调用

#include <unistd.h>
#include <sys/stat.h>
#include <fontl.h>
#include <stdlib.h>

int main()
{
char block[1024];
int in,out;
int nread;

in = open("file.in",O_RDONLY);
out = open("file.out",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);
while((nread = read(in,block,sizeof(block))) > 0)
    write(out,block,nread);
exit(0);
}

$rm file.out
$TIMEFORMAT="" time copy_block
0.00usr 0.01system 0:00.01elapsed 62%CPU
}