文件的打开与关闭

//x像文件中写入数据
#includ<stdio.h>
#include<string,h>
#cinldue<fcntl.h>
#include,unistd.h>

int main(void)[
       //打开文件
    int  fd =  open("./shared.txt",O_WRONLY|O_CREAT|O_TRUNC,0664;
    if(fd==-1){
        perror("open");
        return -1;
    }
   //向文件中写入数据
    char* buf = "hello word";
    ssize_t size=write(fd,buf,strlen(buf));
    if(size==-1){
         perror("write");
         return -1;
        }
        printf("实际写入%ld个字节数\n",size);
  
    //关闭文件
    close(fd); 
    return 0;
}
//读取文件
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>

int main(void){
     //打开文件
      int fd= open("./shared.txt",O_RDONLY);
      if(fd==-1){
           perror("open");
            return -1;
            }
        //读取文件
        char buf[64];//用来存储读取到的数据
        ssize_t size=read(fd,buf,sizeof(buf)-1);
        if(size==-1){
        perror("read");
        return -1;
        }
        printf("实际读取到%ld个字节\n",size);
        printf("%s\n",buf);

        //关闭文件
        close(fd);

    return 0;
}

2.顺序读写与随机读写

//调整文件的读写文字hi
#include<stdio.h>
#include<string.h>
#include<unisted.h>
        //打开文件
        open("./lseeek.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
        if(fd==-1){
        perror("open");
        return -1;
        }
        //像文件中写入数据 hello word
        char* buf="hello word!";
        if(write(fd,buf,strlen(buf))==-1){
            perror("write");
            return -1;    
        }
        //修改文件读写位置
        IF(lseek(fd,-6,SEEK_END)==-1){
        perror("lseek");
        return -1;
        }
        //再次向文件写入数据 Liunx!
        buf="liunx!";
        if(write(fd,buf,strlen(buf))==-1){
            perror("write");
            return -1; 
          }   
        //关闭文件
         close(fd);

2.文件描述符的复制

 //文件描述符的复制
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>

int main(void){
    //打开文件,得到文件描述符  oldfd
    int  oldfd =  open("./dup.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
    if(old==-1){
     perror("open")
     return -1;
}
    //复制文件描述符
     int newfd=dup(oldfd);
     if(newfd==-1){
      perror("dup");
      return -1;
}
     printf("newfd=%d\n",newfd)
    //通过oldf向文件写入helloword;
     char*buf="hello world";
     if(write(oldfd,buf,strlen(buf))==-1){
        perror("write");
        return -1;
    }
    //通过newfold调整文件读写位置
    if(lseek(newfd,-6,SEEK_END)==-1){
       peror("lseeek");
       return -1;
    }

     buf="linux";
    //通过oldfd再次向文件写入数据
       if(write(oldfd,buf,strlen(buf))==-1){
        perror("write");
        return -1;
      }

     //关闭文件 

   close(newfd);
   close(oldfd);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值