zoukankan      html  css  js  c++  java
  • Linux 文件IO简单实例

    目录

     

    简述

    代码

    编译运行


    简述

    Linux下的所有资源都被抽象为文件,所以对所有资源的访问都是以设备文件的形式访问,设备文件的操作主要包括:打开、关闭、读、写、控制、修改属性等。下面的示例代码主要是对文本文件的拷贝。

    其实对于一些复杂一点的设备,主要操作也是类似,比如摄像头,在linux下也是一个设备文件,打开之后,可以读取摄像头的参数,然后可以读取图像数据,读取到的图像数据可以编码后保存到文件中,这就是录像的过程,也可以把读到的图像数据送到LCD显示屏的帧缓存去显示出来。

    再比如串口的操作,在Linux下,对于串口通信,也是设备文件的读写操作:打开设备文件--->配置参数(波特率、停止位、校验位等)--->读取/写入数据。

    代码

    #include <stdio.h>
    #include <unistd.h>
    #include <string.h>
    #include <fcntl.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    
    
    #define M 128
    
    int 
    main(int argc, char **argv)
    {
        if(argc < 3){
            printf("Usage:%s,<file1>,<file2>
    ",argv[0]);
            return -1;
        }
    
        int fd1,fd2;
        char buf[M];
        int count = -1;
    
        memset(buf, '', M);
        if((fd1 = open(argv[1],O_RDONLY)) == -1){
            perror("open file1 error:");
            return -1;
        }
        if((fd2 = open(argv[2],O_RDWR | O_CREAT,0644)) == -1){
            perror("open file2 error:");
            return -1;
        }
    	
        while(count != 0){
            if((count = read(fd1,buf,M)) == -1){
                perror("read file1 error:");
                return -1;
            }
    
            if((count = write(fd2,buf,count)) == -1){
                perror("write error:");
                return -1;
            }
        }
        close(fd1);
        close(fd2);
        return 0;
    }
    

    编译运行

    gcc copy.c -o copy
    
    ./copy copy test
    
    $ ls
    copy  copy.c  test
    
    $ diff copy test  
    $
    

    运行结果,程序对其自身拷贝了一份为test的文件,用diff命令比较两个文件,没有差异,完全一样,说明拷贝成功了。

  • 相关阅读:
    使用阿里的EasyExcel实现表格导出功能
    推荐一款实用的java工具包---Hutool
    MySQL(二)锁机制【表级锁、页面锁、行级锁】
    MySQL(一)存储引擎
    使用redis的increment()方法实现计数器功能
    Redis缓存浅析
    Dubbo服务介绍
    SpringMVC工作执行流程详解
    GC垃圾回收机制----GC回收算法(GC机制必会知识点)
    数据结构之常见的数据结构
  • 原文地址:https://www.cnblogs.com/fensnote/p/13436446.html
Copyright © 2011-2022 走看看