嵌入式学习28(linux系统函数之文件、文件夹管理相关函数)

步入linux系统函数的学习了,随时随地都要man一下,忌死记。

linux系统调用:即linux操作系统提供的函数,只能用于linux。
命令就是一些函数
1)文件系统管理相关的系统调用
文件相关操作
file:存放在外存设备上的一堆数据(内存和外存的交互,外存数据存取慢)
普通文件操作:(open read write lseek close) 辅助函数(stat chmod chown remove )

示例代码:求文件的md5加密

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "md5.h"

//#define _DEBUG 便于调试
int get_file_size(const char* name);
int main(int argc,char** argv)
{
    if(argc!=2)
    {
        fprintf(stderr,"参数个数错误!\n");//标准错误打印
        return -1;
    }
    //open函数的返回值为文件描述符,用来唯一的标识打开的文件
    int fd=open(argv[1],O_RDONLY);
    if(-1==fd)
    {
        perror("open");//自动添加冒号和原因
    }

    int len;//存放文件长度
    len=get_file_size(argv[1]);
    char* buf=malloc(len);

    read(fd,buf,len);//把文件存到内存
#ifdef _DEBUG
    printf("文件长度: %d\n文件内容:\n%s",len,buf);
#endif
    char* md5_val=md5_encrypt(buf,len);
    printf("%s\n",md5_val);
    free(buf);
    close(fd);
    return 0;
}
int get_file_size(const char* name)
{
    struct stat st;
    if(-1==stat(name,&st))//stat可以求出一个文件的所有信息
    {
        perror("get_file_size");//系统打印错误//打印
        return -1;
    }
    return st.st_size;
}

文件夹相关操作(opendir readdir closedir)

//文件夹的遍历
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
void main(int argc,char** argv)
{
    if(2!=argc)
    {
        printf("参数不足\n");
        return;
    }
    DIR* dir=opendir(argv[1]);
    if(dir==NULL)
    {
//      fprintf(stderr,"opendir:%s\n",strerror(errno));
//      strerror可以将错误代号翻译成一串字符串,errno用于存放最近一次的错误
        perror("opendir");//errno is set appropriately
        return;
    }

    struct dirent* rp=NULL;
    struct stat st;//stat中含有文件详细信息
    char name[100];
    while(rp=readdir(dir))//while(后接表达式)
    {
            sprintf(name,"%s/%s",argv[1],rp->d_name);
            stat(name,&st);
            if(S_ISDIR(st.st_mode))
                    continue;
            if(strcmp(rp->d_name,".")!=0  && strcmp(rp->d_name,"..")!=0)
                    printf("%s\n",rp->d_name);

    }
    closedir(dir);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值