Linux的文件I/O函数的总结(文件编程小结一)

文件编程小结(一)

项目目的:掌握并懂得如何应用常用的linux文件I/O函数:open、read、write、close 、lseek。

open:

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>

       int open(const char *pathname, int flags);
       int open(const char *pathname, int flags, mode_t mode);

       int creat(const char *pathname, mode_t mode);

/*

函数的参数:

pathname:    打开文件的路径名
flags:       用来控制打开文件的模式
mode:        用来设置创建文件的权限(rwx)。当flags中带有O_CREAT时才有效

返回值:       成功则返回文件描述符,否则返回 -1

flags参数详解:
O_RDONLY      只读模式
O_WRONLY      只写模式
O_RDWR        读写模式

打开/创建文件时,至少得使用上述三个常量中的一个。以下常量是选用的:

O_APPEND       每次写操作都写入文件的末尾
O_CREAT        如果指定文件不存在,则创建这个文件
O_EXCL         如果要创建的文件已存在,则返回 -1,并且修改 errno 的值
O_TRUNC        如果文件存在,并且以只写/读写方式打开,则清空文件全部内容
O_NOCTTY       如果路径名指向终端设备,不要把这个设备用作控制终端。
O_NONBLOCK     如果路径名指向 FIFO/块文件/字符文件,则把文件的打开和后继 I/O设置为非阻塞模式(nonblocking mode)
*/

  注意点:使用open系统调用打开文件后,会返回对应文件的文件描述符fd(file description),该文件描述符将作为后面read、write、close系统调用的输入参数

 

read:


SYNOPSIS
       #include <unistd.h>

       ssize_t read(int fd, void *buf, size_t count);

/*DESCRIPTION
       read()  attempts to read up to count bytes from file descriptor fd into
       the buffer starting at buf.

       If count is zero, read() returns zero and has  no  other  results.   If
       count is greater than SSIZE_MAX, the result is unspecified.

RETURN VALUE
       On success, the number of bytes read is returned (zero indicates end of
       file), and the file position is advanced by this number.  It is not  an
       error  if  this  number  is smaller than the number of bytes requested;
       this may happen for example because fewer bytes are actually  available
       right  now  (maybe  because we were close to end-of-file, or because we
       are reading from a pipe, or from a terminal),  or  because  read()  was
       interrupted  by  a  signal.  On error, -1 is returned, and errno is set
       appropriately.  In this case it is left unspecified  whether  the  file
       position (if any) changes.

该函数有三个参数:fd表示文件描述符,调用open函数打开文件后,会返回该值;
                buf用于存放读到的数据;
                count表示读取的字节数。
该函数原型的返回值为ssize_t,大于0时,表示读取到buf中的字节数;小于0时,表示返回错误;为0时,表示读取到文件的末尾即EOF。



*/

 

write:

SYNOPSIS
       #include <unistd.h>

       ssize_t write(int fd, const void *buf, size_t count);
/*
DESCRIPTION
       write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd.

       The  number  of  bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the
       RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler  after  having  written  less
       than count bytes.  (See also pipe(7).)

       For  a  seekable file (i.e., one to which lseek(2) may be applied, for example, a regular file) writing takes place at the current file off‐
       set, and the file offset is incremented by the number of bytes actually written.  If the file was open(2)ed with O_APPEND, the  file  offset
       is  first  set  to the end of the file before writing.  The adjustment of the file offset and the write operation are performed as an atomic
       step.

       POSIX requires that a read(2) which can be proved to occur after a write() has returned returns the new data.  Note that not all  file  sys‐
       tems are POSIX conforming.

RETURN VALUE
       On success, the number of bytes written is returned (zero indicates nothing was written).  On error, -1 is returned, and errno is set appro‐
       priately.

       If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is  detected.   If  no
       errors  are  detected,  0  will be returned without causing any other effect.  If count is zero and fd refers to a file other than a regular
       file, the results are not specified.


①write说明:write()会把参数buf所指的内存写入count个字节到参数放到所指的文件内。

②返回值说明:如果顺利write()会返回实际写入的字节数。当有错误发生时则返回-1,其中呢错误代码存入errno中。

③write()函数从buf写数据到fd中时,若buf中数据无法一次性读完,那么第二次读buf中数据时,其读位置指针(也就是第二个参数buf)不会自动移动,需要程序员编程控制,而不是简单的将buf首地址填入第二参数即可。如可按如下格式实现读位置移动:write(fp, p1+len, (strlen(p1)-len)。 这样write第二次循环时变会从p1+len处写数据到fp, 之后的也由此类推,直至(strlen(p1)-len变为0。

④在write一次可以写的最大数据范围内(貌似是BUFSIZ ,8192),第三参数count大小最好为buf中数据的大小,以免出现错误。(经过笔者再次试验,write一次能够写入的并不只有8192这么多,笔者尝试一次写入81920000,结果也是可以,看来其一次最大写入数据并不是8192,但内核中确实有BUFSIZ这个参数,具体指什么还有待研究)


*/

 

注:

lseek:

SYNOPSIS
       #include <sys/types.h>
       #include <unistd.h>

       off_t lseek(int fd, off_t offset, int whence);
/*
/DESCRIPTION
       The  lseek() function repositions the offset of the open file associated with the file descriptor fd to the argument offset according to the
       directive whence as follows:

       SEEK_SET
              The offset is set to offset bytes.

       SEEK_CUR
              The offset is set to its current location plus offset bytes.

       SEEK_END
              The offset is set to the size of the file plus offset bytes.

RETURN VALUE
       Upon  successful  completion,  lseek() returns the resulting offset location as measured in bytes from the beginning of the file.  On error,
       the value (off_t) -1 is returned and errno is set to indicate the error.


注:lseek()函数会重新定位被打开文件的位移量,由offset以及whence的组合来决定:
SEEK_SET: 
  从文件头部开始偏移offset个字节。 
SEEK_CUR: 
  从文件当前读写的指针位置开始,增加offset个字节的偏移量。 
SEEK_END: 
  文件偏移量设置为文件的大小加上偏移量字节。


*/

close:

SYNOPSIS
       #include <unistd.h>

       int close(int fd);

/*
DESCRIPTION
       close()  closes  a  file descriptor, so that it no longer refers to any file and may be reused.  Any record locks (see fcntl(2)) held on the
       file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).

       If fd is the last file descriptor referring to the underlying open file description (see open(2)), the resources associated  with  the  open
       file description are freed; if the descriptor was the last reference to a file which has been removed using unlink(2) the file is deleted.

RETURN VALUE
       close() returns zero on success.  On error, -1 is returned, and errno is set appropriately.
   

close 一个套接字的默认行为是把套接字标记为已关闭,然后立即返回到调用进程,该套接字描述符不能再由调用进程使用,也就是说它不能再作为read或write的第一个参数,然而TCP将尝试发送已排队等待发送到对端的任何数据,发送完毕后发生的是正常的TCP连接终止序列。

    在多进程并发服务器中,父子进程共享着套接字,套接字描述符引用计数记录着共享着的进程个数,当父进程或某一子进程close掉套接字时,描述符引用计数会相应的减一,当引用计数仍大于零时,这个close调用就不会引发TCP的四路握手断连过程。

*/

 

看完这些,不妨试一试小项目检验一下掌握程度:实现linux 的cp指令的代码

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值