004_Linux文件IO操作之open(),read(),write()函数

1.open()函数依赖的头文件

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

2.函数声明

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);```

函数说明:
① open()函数打开文件后,返回的是文件夹描述符(也是Windows编程句柄的概念)。
②新打开文件返回文件描述符表中未使用的最小文件描述符。
③open返回值:成功返回新分配的文件描述符,出错返回-1并设置errno
3.open的flag有一下几个可选项
O_CREAT 创建文件
O_EXCL 创建文件是,如果文件存在则出错返回
O_TRUNC 把文件截断成0
O_RDONLY 只读(互斥)
O_WRONLY 只写(互斥)
O_RDWR 读写(互斥)
O_APPEND 追加,移动文件读写指针位置到文件末尾
O_NONBLOCK 非阻塞标志
O_SYNC 使每次write都等到物理I/O操作完成,包括文件属性的更新
4.关于文件描述符
一个进程默认打开3个文件描述符
STDIN_FILENO 0
STDOUT_FILENO 1
STDERR_FILENO 2
新打开文件返回文件描述符表中未使用的最小文件描述符。
open()函数可以打开或创建一个文件
5.在操作系统中默认允许代开的文件数数量是1024个文件

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

void test()
{
	int fd;
	char name[1024];
	int i = 0;
	while(1)
	{
		sprintf(name, "file%d", ++i);
		fd = open(name, O_CREAT, 0777);
		if(fd == -1)
			exit(1);
			printf("%d\n", i);
	}
}

int main()
{
	test();
	return 0;
}

6.文件复制

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

#define SIZE    8192

int main(int argc, char *argv[])
{
    char buf[SIZE];
    int fd_src, fd_dest, len;
    if (argc < 3) {
        printf("./mycp src dest\n");
        exit(1);
    }
    fd_src = open(argv[1], O_RDONLY);
    fd_dest = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0644);
    /*
     * 成功返回读到字节数
     * 读到文件末尾返回0
     * 读失败返回-1
     */ 
    while ((len = read(fd_src, buf, sizeof(buf))) > 0)
        write(fd_dest, buf, len);
    close(fd_src);
    close(fd_dest);
    return 0;
}
注意:要注意的是要传入源文件和目标文件。

7.创建文件的时候,使用umask

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

int main(int argc, char *argv[])
{
    int fd;
    char buf[1024] = "hello";
    if (argc < 2) {
        printf("./app filename\n");
        exit(1);
    }
    //设置mask的值为0
    umask(0); 
    fd = open(argv[1], O_CREAT | O_RDWR | O_EXCL, 0777);
    printf("fd = %d\n", fd);
    close(fd);

    return 0;
}

8.read()和write()
read函数从打开的设备文件中读取数据
①依赖的头文件
#include<unistd.h>
②函数声明
ssize_t read(int fd,void *buf,size_t count);
返回值:成功返回读取的字节数,出错返回-1,并设置errno,如果在调用read文件前已经到到达文件末尾,则这次read返回0

9.write函数向打开的设备文件中写数据
①依赖的头文件
#include<unistd.h>
②函数声明
ssize_t write(int fd,const void *buf,size_t count);
返回值:成功返回写入的字节数,出错返回-1,并设置errno
注意:写常规文件时,write的返回值通常等于请求写的字节数count,而向终端设备或网络写则不一定。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值