zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    Chapter 12 homework
    copy construction note
    Chapter 11 homework
    数组排序最大元素
    temporary Object and destructor
    strcpy() 函数注意的地方
    结对项目第二次作业
    结队项目——第一次作业
    软件工程实践2017第二次作业
    软件工程实践2017第一次作业
  • 原文地址:https://www.cnblogs.com/dayq/p/15362082.html
Copyright © 2011-2022 走看看