Linux操作文件的底层系统调用

C语言操作文件的几个库函数:fopen,fread,fwrite,fclose;

系统调用:open,read,write,close;

系统调用方法实现在内核中;(陷入内核,切换到内核)

 1、系统调用的介绍

(1)open():打开一个文件

open重载:两个参数用于打开一个已经存在的文件;三个参数的用于新建一个文件,并设置访问权限;

参数:

pathname:文件的路径和名称;

flags:文件的打开方式;

mode:文件的权限,如"0600";

返回值:

为int,称为文件描述符;(Linux上一切皆文件)

flags的打开标志,如:

O_WRONLY:只写打开;

O_RDONLY:只读打开;

O_RDWR:读写方式打开;

O_CREAT:文件不存在则创建;

O_APPEND:文件末尾追加;

O_TRUNC:清空文件,重新写入;

(2)write():向文件中写入数据

头文件:<unistd.h>

参数:

fd:对应打开的文件描述符

buf:写入的文件内容;

count:要写入多少个字节;

返回值:

ssize_t:实际写入了多少个字节;

(3)read():从文件中读取数据

头文件:<unistd.h>

参数:

fd:对应打开的文件描述符;

buf:把文件内容读取到一块空间buf中;

count:期望要读取的字节数;

返回值:

ssize_t:实际读取了多少个字节;

(4)close():关闭文件

关闭文件描述符;

(5)文件描述符:

文件打开以后,内核给文件的一个编号;(>0的整数)

标准输入对应的编号:0   stdin

标准输出对应的编号:1   stdout

标准错误输出对应的编号:2   stderror

文件描述符是最小未被使用的一项;

2、文件系统调用的应用实例

(1)打开一个文件并往里面写入hello

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
int main()
{
int fd=open("file.txt",O_WRONLY|O_CREAT,0600);
assert(fd!=-1);
printf("fd=%d\n",fd);
write(fd,"hello",5);
close(fd);
exit(0);
}

(2)打开文件,读取文件内容

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
int main()
{
int fd=open("file.txt",O_RDONLY);
assert(fd!=-1);
char buff[128]={0};
int n=read(fd,buff,127);
printf("n=%d,buff=%s\n",n,buff);
close(fd);
exit(0);
}

(3) 利用读和写对文件进程复制

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>

int main()
 {
     int fdr=open("file.txt",O_RDONLY);
     int fdw=open("newfile.txt",O_WRONLY|O_CREAT,0600);
 
     if(fdr==-1||fdw==-1)
     {
          exit(0);
     }
 
     char buff[256]={0};
     int num=0;
     while((num=read(fdr,buff,256))>0)
     {
         write(fdw,buff,num);
     }
     close(fdr);
     close(fdw);

     exit(0);
}
             

(4)实现类似cp命令

./main  file.txt  newfile.txt

cp  file.txt  newfile.txt

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>

int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        printf("arg error\n");
    }
    char *file_name=argv[1];
    char *newfile_name=argv[2];
    int fdr=open(file_name,O_RDONLY);
    int fdw=open(newfile_name,O_WRONLY|O_CREAT,0600);

    if(fdr==-1||fdw==-1)
    {
         exit(0);
    }
 
    char buff[256]={0};
    int num=0;
    while((num=read(fdr,buff,256))>0)
    {
        write(fdw,buff,num);
    }
    close(fdr);
    close(fdw);
 
   exit(0);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值