c语言,U盘发现器、盗墓者是个丑奴儿

//盗墓者是个丑奴儿,原

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/types.h>

//参数:文件目录路径

//返回值:返回检测目录路径下的文件个数,readdir为NULL退出。如果存在错误返回-1

int find_mtp(char * pathname){
        struct stat buf={0};
        if(S_ISDIR(buf.st_mode))
        return -1;
        DIR * dir=opendir(pathname);
        if(dir==NULL)
        return -1;
        struct dirent * read=NULL;
        int index=0;
        while(1){
                read=readdir(dir);
                if(read==NULL)
                break;
                index++;
        }
        return index;
}

//main方法测试

//将find_mtp参数替换为u盘所在的目录位置即可

//通过记录的长度与实时探测的长度,进行对比,判断是否插入与取出u盘

int main(void){
        int i=find_mtp("/home/daomu/c");
        int y=0;
        while(1){
                sleep(1);
                y=find_mtp("/home/daomu/c");
                if(i<y)
                printf("insert U; \n");
                if(i>y)
                printf("take out U; \n");
                i=y;
        }

        return 0;
}

运行结果:通过对检测的目录,增加与删除目录来验证是否达到基本功能。由于插入u盘也是增加目录,取出u盘也是取消目录。所以虽然没有以u盘测试,但是逻辑符合。

猜你喜欢

转载自blog.csdn.net/java_dmz/article/details/81127485