Linux 系统IO函数
1.open函数
# 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) ;
int openat ( int dirfd, const char * pathname, int flags) ;
int openat ( int dirfd, const char * pathname, int flags, mode_t mode) ;
flags:
O_RDONLY: 以只读方式打开文件
O_WRONLY:以只写方式打开文件
O_RDWR: 以读写方式打开文件
O_CREAT: 如果文件不存在,则创建一个文件,并且需要指定文件的属性(umask)
O_TRUNC:如果文件已经存在,并且文件可写,会把文件截断为0
O_APPEND:以追加写的方式写文件
ex:
# include <unistd.h>
# include <error.h>
int fd = - 1 ;
fd = open ( "path" , O_RDWR) ;
if ( fd == - 1 ) ;
printf ( "fd = %d, error:%d %s" , fd, errno, strerror ( errno) ) ;
2.read函数
# include <unistd.h>
ssize_t read ( int fd, void * buf, size_t count) ;
3.write函数
# include <unistd.h>
ssize_t write ( int fd, const void * buf, size_t count) ;
4.close函数
# include <unistd.h>
int close ( int fd) ;
实现拷贝函数
# include <unistd.h>
# include <stdio.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <fcntl.h>
# include <errno.h>
# include <string.h>
int main ( int argc, char * argv[ ] )
{
int fd1 = - 1 ;
int fd2 = - 1 ;
char buf[ 1024 ] = { 0 } ;
int len = 0 ;
if ( argc < 2 )
printf ( "input params fail\n" ) ;
fd1 = open ( argv[ 1 ] , O_RDWR) ;
if ( fd1 == - 1 )
printf ( "errno:%d fd = %d %s\n" , errno, fd1, strerror ( errno) ) ;
fd2 = open ( argv[ 2 ] , O_RDWR | O_CREAT, 0644 ) ;
if ( fd2 == - 1 )
printf ( "errno:%d fd=%d %s\n" , errno, fd2, strerror ( errno) ) ;
while ( len = read ( fd1, buf, sizeof ( buf) ) ) {
write ( fd2, buf, len) ;
}
close ( fd1) ;
close ( fd2) ;
return 0 ;
}
5.fcntl函数
# include <unistd.h>
# include <fcntl.h>
fd:
cmd: F_GETFD 获取fd信息 arg:void return : fd的参数
F_SETFD 设置fd参数 arg:int
int fcntl ( int fd, int cmd, . . . ) ;
6.lseek函数
# include <sys/types.h>
# include <unistd.h>
fd:需要操作的文件描述符
offset: 偏移的大小
whence:位置的位置
SEEK_SET : 自定义设置的偏移量
SEEK_CUR :光标设置到当前位置
SEEK_END :光标设置到文件结束位置
off_t lseek ( int fd, off_t offset, int whence) ;
int fd = - 1 ;
int lenth = 0 ;
fd = open ( "path" , O_RDONLY) ;
if ( fd == - 1 )
{
printf ( "open fail\n" , strerror ( errno) ) ;
return - 1 ;
}
lenth = lseek ( fd, 0 , SEEK_END ) ;
printf ( "lenth:%d" , lenth) ;
7.mmap函数
# include <sys/mman.h>
映射文件或者设备到内存中
void * mmap ( void * addr, size_t length, int prot, int flags,
int fd, off_t offset) ;
int munmap ( void * addr, size_t length) ;
8.prctl函数
# include <sys/prctl.h>
通常同来给线程设定线程名
int prctl ( int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5) ;