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("文件创建失败!\n");
                return 0;
        }
        unsigned char text[] = "this is a test file.";
        size_t fileSize = write(newfile,text,sizeof text);
        printf("已经写入文件大小: %d\n",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("文件打开失败!\n");
                return 0;
        }
        unsigned char *text;
        off_t fileSize = lseek(newfile,0,SEEK_END);//获取文件大小
        printf("文件大小:%d\n",fileSize);
        text = (unsigned char*)malloc(fileSize);
        lseek(newfile,0,SEEK_SET);
        ssize_t size = read(newfile,(char*)text,fileSize);
        printf("已经读取文件大小: %d\n",size);
        printf("读取数据: %s\n",text);
        close(newfile);
        return 0;
}

 

posted @ 2021-10-02 16:02  念秋  阅读(337)  评论(0编辑  收藏  举报