嵌入式學習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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章