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

来源:互联网 发布:javaweb邮件系统源码 编辑:程序博客网 时间:2024/06/05 17:56

步入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 0
原创粉丝点击