嵌入式文件IO

文件IO

文件IO的概念:
什么是文件IO,又称系统IO,系统调用
是操作系统提供的API接口函数。
POSIX接口 (了解)
注意:文件IO不提供缓冲机制

文件IO的API
open close read write

文件描述符概念:
英文:缩写fd(file descriptor)
是0-1023的数字,表示文件。
0, 1, 2 的含义 标准输入,标准输出,错误

文件IO 打开
open
int open(const char *pathname, int flags); 不创建文件
int open(const char *pathname, int flags, mode_t mode); 创建文件,不能创建设备文件
成功时返回文件描述符;出错时返回EOF

在这里插入图片描述

文件IO和标准的模式对应关系:

r				O_RDONLY
r+				O_RDWR
w				O_WRONLY | O_CREAT | O_TRUNC, 0664
w+				O_RDWR | O_CREAT | O_TRUNC, 0664
a				O_WRONLY | O_CREAT | O_APPEND, 0664
a+				O_RDWR | O_CREAT | O_APPEND, 0664

umask概念:
umask 用来设定文件或目录的初始权限

文件的关闭
int close(int fd)
关闭后文件描述符不能代表文件

文件IO的读写和定位

容易出错点:
求字符串长度使用strlen,对二进制数据使用sizeof
printf 的字符最后没有’\0’

关闭打开文件函数如下:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[]){
    int fd;
    int ret;
     
    fd = open("test.txt",O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if(fd<0){
       printf("open file err\n");
       return 0;

    }
    printf("sucess,fd=%d\n",fd);

    ret=  close(fd);
    if(ret<0){
        printf("close failed\n");
    }

    ret=close(fd);
    printf("ret=%d\n",ret);
}

读写文件

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

int main(int argc,char *argv[]){

    int fd;
    int ret;
    char buf[32] = "hello world";
    char buf2[32]={0};
    fd = open("test.txt",O_RDWR | O_CREAT | O_APPEND, 0666);
    if(fd<0)
    {
       printf("open file err\n");
       return 0;
    }
    printf("sucess,fd=%d\n",fd);
    ret=write(fd,buf,strlen(buf));//写字符串用strlen不用sizeof,写二进制时用sizeof
    if(ret<0)
    {
       perror("write");
       close(fd);
       return 0;
    }
    printf("write count=%d\n",ret);
    lseek(fd,0,SEEK_SET);
    //close(fd);                 	让文件指针归零
    //fd = open("test.txt",O_RDWR | O_CREAT | O_APPEND, 0666);  这两条在此程序作用同上一条
    ret = read(fd,buf2,32);
    if(ret<0)
    {
        perror("read");
        close(fd);
        return 0;
    }
    buf2[31]=0;
    printf("read buf2=%s\n",buf2);
    close(fd);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嵌入式学习者。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值