linux编程基础—文件I/O编程

Linux文件I/O主要由read、write、open、close、lseek五个函数组成;

一、文件描述符

在嵌入式Linux中每打开一个文件都有一个描述符与之对应,该描述符是一个非负整数;

当用open打开或新建一个文件时,该函数的返回值就是该文件的描述符;

当调用read、write函数来读写文件时,将文件描述符作为参数传进去;

二、函数介绍

1、open函数

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

函数形式:

int open(const char pathname, int oflag)

参数:一般使用两个参数

但创建文件时,会用到第三个参数

返回值:函数调用成功返回文件描述符

失败返回 -1

pathname—打开或创建文件的文件名;

oflag——控制标志,时多个常数进行或运算的结果,常见的标志有:

O_RDONLY:打开只读

O_WRONLY:打开只写

O_RDWR:打开读、写

以上三选一

以下可多选

O_CREAT:若文件不存在,则创建,此选项与第三个单数配合使用,来决定该文件的存取权限;

O_APPEND:每次向文件写入数据都添加到文件末尾;

O_EXLC:

O_TRUNC:

2、close函数

#include<unistd.h>

函数形式:

int close(int filedes)

该函数用来关闭一个文件,释放该文件上的记录锁

返回值: 成功——0

失败—— -1

3、read函数

#include<unistd.h>

函数形式:

ssize_t read(int filedes, void* buf, size_t nbytes)

参数:

filedes:文件标示符

buf: 目标文件缓冲地址

size: 读取字节数

返回值:

成功——返回读到的字节数

读到文件结尾—— 0

失败—— -1

4、write函数

#include<unistd.h>

函数形式:

ssize_t write(int filedes, const void* buf, ssize_t nbytes)

参数:

filedes:文件标示符

buf: 源文件缓冲地址

nbytes: 写入字节数

返回值:

成功—— 返回写入的字节数

出错—— -1

5、lseek函数

每打开一个文件都关联着一个文件位移量,用来标识读或写文件时的起始位置;

默认情况下打开一个文件,除非指定O_APPEND选项,否则在文件开头的位置;

但是可以通过调用lseek函数来重新设置文件位移量

#include<sys/types.h>

#include<unistd.h>

函数形式:

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

参数:

fieldes:文件标识符

offset:偏移量

whence:偏移起始位置

SEEK_SET——从文件开始处偏移offset个字节;

SEEK_CUR——从当前位置偏移offset个字节,offset可正可负;

SEEK_END——文件末尾偏移 offset个字节, offset可正可负;

返回值:

成功——返回新的文件偏移量

失败—— -1

三、应用实例

#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<stdio.h>#include<string.h>

int main(void){ int fd; char *p = “hello,world/n”; char buf[15];

if((fd = open(“hello.txt”,O_WRONLY)) == -1)//打开已经存在的文件 “hello.txt” { printf(“open file failed/n”); return -1;} else{ printf(“file has been opened./n”);}

if(write(fd,p,strlen(p)) < strlen(p)) //将“hello,world/n”写入 hello.txt 中{ printf(“write error/n”); close(fd); return -1; } else { printf(“has witten %d nbytes/n”,strlen(p)); }

lseek(fd,5,SEEK_END); //将文件的起始位置定位到文件末尾偏移5个字节处

if(write(fd,p,strlen(p)) < strlen(p)) //再次写入“hello,world/n” { printf(“write error/n”); close(fd); return -1; }else { printf(“has witten %d nbytes/n”,strlen(p)); }

if(read(fd,buf,strlen(p)) < strlen(p)) //将“hello.txt”中的内容读出并显示到屏幕上 { printf(“read failed/n”); close(fd); return -1; } else { printf(“the buf is %s/n”,buf); }

close(fd); //关闭文件

return 0;}

你曾经说,等我们老的时候,

linux编程基础—文件I/O编程

相关文章:

你感兴趣的文章:

标签云: