Linux文件IO编程

Linux文件IO编程

文件 IO 是 Linux 系统提供的接口, 针对文件和磁盘进行操作, 不带缓存机制; 标准 IO 是 C 语言函数库里的标准 I/O 模型, 在 stdio.h 中定义, 通过缓冲区操作文件, 带缓存机制。 Linux 系统中一切皆文件, 包括普通文件, 目录, 设备文件(不包含网络设备) , 管道, fifio 队列, socket 套接字等, 在终端输入“ls -l”可查看文件类型和权限。
标准 IO 和文件 IO 常用 API 如下:
在这里插入图片描述标准 IO 和文件 IO 的区别如下图所示:
在这里插入图片描述
文件 IO 是直接调用内核提供的系统调用函数, 头文件是 unistd.h, 标准 IO 是间接调用系统调用函数,头文件是 stdio.h, 文件 IO 是依赖于 Linux 操作系统的, 标准 IO 是不依赖操作系统的, 所以在任何的操作系统下, 使用标准 IO, 也就是 C 库函数操作文件的方法都是相同的。对于文件 IO 来说, 一切都是围绕文件操作符来进行的。 在 Linux 系统中, 所有打开的文件都有一个对应的文件描述符。 文件描述符的本质是一个非负整数, 当我们打开一个文件时, 系统会给我们分配一个文件描述符。 当我们对一个文件做读写操作的时候, 我们使用 open 函数返回的这个文件描述符会标识该文件,并将其作为参数传递给 read 或者 write 函数。 在 posix.1 应用程序里面, 文件描述符 0,1,2 分别对应着标准输入, 标准输出, 标准错误。文件描述符是一个非负的整数,它是一个索引值,并指向在内核中每个进程打开文件的记录表。

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

1.文件IO open( )


Flags标记

  • O_RDONLY就表示以只读方式打开

  • O_WRONLY表示以只写方式打开

  • O_RDWR表示以可读可写方式打开

当打开已存在并且内部有内容的文件时

  • O_APPEND标志:以添加方式打开文件,在打开文件的同时,文件指针指向文件的末尾,即将写入的数据添加到文件的末尾

  • O_TRUNC标志:若文件已经存在,那么会删除文件中的全部原有数据,并且设置文件大小为0

2.文件IO close( )

实验代码:

编写程序,在同一目录下打开并创建一个可读可写文件,获取完属性后关闭。

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


int main(int argc,char *argv[])
{
	int fd;
    fd = open("hello.c", O_CREAT|O_RDWR, 0666);
    if(fd < 0)
    {
        printf("文件打开错误!\n");
    }
	printf("fd is %d\n", fd);
    close(fd);
    return 0;
}

3.文件IO read( ) write( )

文件读写


#include <unistd.h>
    
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);

在程序中通过命令行操作, 把 hello.c 文件里面的内容写到 world.c

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

int main()
{
	int srcid, dstid;          /* 文件描述符 */
	unsigned char buf[1024];   /* 文件缓存buf */
	int readlen;               /* 文件读取长度 */
	
	memset(buf, 0x00, 1024);   /* memset函数清除 */
    srcid = open("hello.c", O_RDONLY);  /* 文件以只读形式打开 */
	
	if(srcid < 0)
	{
		printf("打开文件出错\n");
		return 0;
	}
    dstid = open("world.c", O_WRONLY|O_CREAT);
    if(dstid < 0)
    {
        printf("打开文件出错\n");
        return 0;
    }
    
    while(readlen = read(srcid, buf, 1024) > 0)
    {
        write(dstid, buf, readlen);
    }
    printf("读出数据长度 %d\n", readlen);
    printf("读出数据的内容:\n");
    printf("%s",buf);
    
    close(srcid);
    close(dstid);
    
 }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值