您的位置:首页 > 运维架构 > Linux

Linux系统编程---IO操作

2014-03-30 21:22 288 查看

1.系统调用

系统调用效率较低

1.系统调用开销大,要从用户空间切换到内核空间,然后切换回用户空间

2.系统调用与底层驱动相关,不一定能够按指定一次写完。

write函数

#include <unistd>​

size_t write(int files, const void  *buf, size_t nbytes );
返回值

0:写入字节为0

​-1:写入出错了 错误保存在全局变量errno中

xx:实际写入字节数

read函数

size_t read(int files, const void  *buf, size_t nbytes );
返回值

0:读取字节为0

​-1:读取出错了 错误保存在全局变量errno中

xx:实际读取字节数

open函数​

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

int open(const char *path, int oflags)
int open(const char *path, int oflags, mode_t mode);


oflags



mode



返回值

非负整数:文件描述符

-1:出错

close函数

int close(int files)



程序运行时间及CPU使用率



lseek函数

#include <unistd>
#include <sys/types.h>(off_t 定义所在)

int lseek(int files, off_t offset, int whence )


whence



返回值

-1:设置失败

xxx:返回偏移实际字节数

2.标准库函数

open函数

​#include <stdio.h>(NULL定义)
FILE * fopen( const char *path, const char *mode)
mode



返回值

非空:文件流指针

NULL:打开失败

fread函数

size_t fread(void * ptr, size_t size, int nitems, FILE *stream)
size 指定记录大小(单位字节)

nitems 读取记录个数

返回值:

非零值:读取到缓冲区的记录数

fwrite函数

size_t fwrite(void * ptr, size_t size, int nitems, FILE *stream)
返回值:

非零值:写到缓冲区的记录数

fclose函数

int fclose(FILE *stream)


fflush函数

int fflush(FILE *stream)


fseek函数

int fseek(FILE *stream, long int offset, int whence)
返回值

-1:操作失败

0:操作成功

fgetc、getc、getchar函数

int fgetc(FILE *stream)
int getc(FILE *stream)
int getchar()


getc可能被实现为宏

getchar返回标准输入流中一个字符

返回值

EOF:出错或到文件尾时

其他:读取的字节

fputc、putc、putchar函数

int fputc(int c, FILE *stream)
int putc(int c, FILE *stream)
int putchar(int c)
返回值

EOF:出错

其他 :写入的字节
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: