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>\n",argv[0]);
        return -1;
    }

    int fd1,fd2;
    char buf[M];
    int count = -1;

    memset(buf, '\0', 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命令比较两个文件,没有差异,完全一样,说明拷贝成功了。

 

微信公众号:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章