• Linux下文件操作API


    仅作为个人记录的参考。

    进程启动,打开3个文件:
    标准输入/输出/错误
    文件描述符为0 1 2.
    STDIN_FILENO/STDOUT_FILENO/STDERR_FILENO

    打开文件:

    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    
    int open(const char* filename,int flags,int perms);
    flags:
    O_RDONLY/O_WRONLY/O_RDWR/O_CREAT/O_TRUNC/O_APPEND
    perms:
    S_I(R/W/X)(USR/GRP/OTH)
    
    成功返回文件描述符,-1则为失败

    关闭文件:

    #include<unistd.h>
    
    int close(int fd);
    传入文件描述符。
    关闭成功返回0,否则为-1

    读取文件:

    #include<unistd.h>
    
    ssize_t read(int fd,void* buff,size_t count)
    返回值:
    -1:出错
    0:文件到达末尾
    否则为读取的字节数

    写文件:

    #include<unistd.h>
    
    ssize_t write(int fd,void* buff,size_t count)
    
    -1:出错
    否则返回写入的字节数

    文件偏移:

    #include<unistd.h>
    #include<sys/types.h>
    
    off_t lseek(int fd,off_t offset,int whence)
    
    移动文件指针到whence+offset的地方,可前后移动。
    whence:
    SEEK_SET/SEEK_CUR/SEEK_END
    
    返回:
    -1:出错
    否则返回文件指针现在的位置

    创建文件并写入内容:

    #include<stdio.h>
    
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    
    #include<unistd.h>
    
    int main()
    {
            int newfile = open("./new.txt",O_CREAT|O_WRONLY,S_IRUSR|S_IWUSR);
            if(newfile==-1)
            {
                    printf("文件创建失败!
    ");
                    return 0;
            }
            unsigned char text[] = "this is a test file.";
            size_t fileSize = write(newfile,text,sizeof text);
            printf("已经写入文件大小: %d
    ",fileSize);
    
            close(newfile);
            return 0;
    }

    读取刚才创建的文件:

    #include<stdio.h>
    
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    #include<string.h>
    #include<unistd.h>
    
    int main()
    {
            int newfile = open("./new.txt",O_RDONLY);
            if(newfile==-1)
            {
                    printf("文件打开失败!
    ");
                    return 0;
            }
            unsigned char *text;
            off_t fileSize = lseek(newfile,0,SEEK_END);//获取文件大小
            printf("文件大小:%d
    ",fileSize);
            text = (unsigned char*)malloc(fileSize);
            lseek(newfile,0,SEEK_SET);
            ssize_t size = read(newfile,(char*)text,fileSize);
            printf("已经读取文件大小: %d
    ",size);
            printf("读取数据: %s
    ",text);
            close(newfile);
            return 0;
    }

  • 相关阅读:
    异常之*** buffer overflow detected ***
    多媒体开发之视频回放---dm642 做rtsp 视频回放功能
    理财---炒股之kdj
    多媒体开发之rtp 打包发流--- 从h264中获取分辨率
    多媒体开发之rtsp 实现rtsp over tcp/http/udp---rtsp发送
    tomcat 简介
    tomcat 的安装
    rsync + inotify-tools实现文件的实时同步
    python 生成器
    ansible 常用模块
  • 原文地址:https://www.cnblogs.com/dayq/p/15362082.html
Copyright © 2020-2023  润新知