UNIX File I/O

Introduction

  • most file I/O on a UNIX system can be performed using only five functions:open,read,write,lseek and close
  • the functions described in this chapter are often unbuffered I/O,,unbuffered means each read or write invokes a system call in the kernel.they are not part of ISO C,are part of POSIX.1 and the Single UNIX Specification.

file descriptors

  • to the kernel,all open files are referred to by file descriptors,it is a non-negtive integer
  • UNIX system shells associate file descriptor 0 with the standard input of a process and 1 with the standard output,2 with the standard err,but it is not a feature of the kernel,we can use STDIN_FILENE,STDOUT_FILENO,STDERR_FILENO to improve the readability which are defined in unistd.h
  • file descriptors range from 0 to OPEN_MAX-1.

open and openat functions

  • a file is opened or created by calling either the open function or the openat function.

filename and pathname truncation

  • if the filename length over the NAME_MAX,some systems truncate the filename beyond the NAME_MAX character,some return an error status

close function

  • close a file will release any record locks that the process may have on the file.
  • when a process terminates,all of its open file will be closed automatically by the kernel

lseek function

  • every open file has a associated “current file offset”,a non-negtive integer measures the number of bytes from the beginning of the file,read of write function often start at the current file offset and cause the offset to be increaed when reading or writing.
  • an open file’s offset can be set explicitly by calling lseek.
  • this technique can also be used to determine if a file is capable of seeking,if the file descriptor refers to a pipe,FIFO,or socket,lseek sets errno to ESPIPE and returns -1.
  • for certain devices,the offset can be negtive
  • the offset can be larger than the file size,in which case the next write to the file extend the file,any bytes in a file that have not been written are read back as 0.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值