Linux软件编程---文件IO

目录

一、目录文件接口

1.1.mkdir

       1. 在终端

        2.软件编程中

        3.注意

1.2.rmdir 

        1. 在终端

         2.软件编程中

 1.3.getcwd

        1.在终端

        2.软件编程中 

 1.4.chdir

        1.在终端

        2.软件编程中 

 1.5.chmod

        1.在终端

        2.软件编程中 

 1.6.实例

二、目录文件读取

2.1.打开目录

        opeandir

2.2.读取目录

        readdir  

2.3.关闭目录

        closedir

2.4.实例 

        实例1.读取某个目录

        2.读取某个目录下以及子目录下的所有目录,并打印查询时间

三、链接文件接口 

3.1.软链接

        1.在终端

        2.软件编程中

        3.注意点

 3.2.硬链接

        1.在终端

        2.在软件编程中 

 3.注意点

 3.3.实例

        1.软链接

        2.硬链接 

四、文件详细接口

4.1.stat和lstat

4.2.实例

五、总结


一、目录文件接口

1.1.mkdir

       1. 在终端

                命令: mkdir 文件名

        2.软件编程中

int mkdir(const char *pathname, mode_t mode);
       功能:
            创建目录 
       参数:
            pathname:目录文件的路径 
            mode:目录文件的权限 
       返回值:
            成功返回0
            失败返回-1 

        3.注意

                r 决定是否目录下可以查看其余文件信息 
                w 决定目录下的文件是否能够新建
                x 决定目录文件是否能够进入

1.2.rmdir 

        1. 在终端

                命令:rmdir 文件名  (注意这里只能删除空目录)

         2.软件编程中

  int rmdir(const char *pathname);
        功能:
            删除空目录文件 
        参数:
            pathname: 
                目录文件的路径
        返回值:
            成功返回0 
            失败返回-1 

 1.3.getcwd

        1.在终端

                命令:pwd

        2.软件编程中 

char *getcwd(char *buf, size_t size);
        功能:
            获得当前工作目录的绝对路径 
        参数: 
            buf:存放路径空间首地址
            size:最大存放字符的长度
        返回值:    
            成功返回存放路径字符串空间首地址
            失败返回NULL

 1.4.chdir

        1.在终端

                命令:cd  .....

        2.软件编程中 

 int chdir(const char *path);
        功能:  
            切换程序当前的工作路径 
        参数:
            path:目的路径  
        返回值: 
            成功返回0 
            失败返回-1 

 1.5.chmod

        1.在终端

                命令:chmod  0777 filrname

                           chmod +/-r/w/x filename 

        2.软件编程中 

int chmod(const char *pathname, mode_t mode);
        功能:
            修改文件权限
        参数:
            pathname:文件路径 
            mode:权限值     0777       0664  
        返回值:
            成功返回0 
            失败返回-1

 1.6.实例

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(void)
{
    char tmpbuffer[128] = {0};

    getcwd(tmpbuffer,sizeof(tmpbuffer));
    printf("%s\n", tmpbuffer);

    chdir("/home/linux/Desktop");
    getcwd(tmpbuffer,sizeof(tmpbuffer));
    printf("%s\n", tmpbuffer);

    mkdir("dirname",0777);
    rmdir("dirname");


    return 0;
}

二、目录文件读取

2.1.打开目录

        opeandir

 DIR *opendir(const char *name);
          功能:
              打开目录
          参数:
              name:目录文件路径
          返回值:
              成功返回目录流指针
              失败返回NULL 

2.2.读取目录

        readdir  

struct dirent *readdir(DIR *dirp);
          功能:
            读取目录项 
          参数:
            dirp:目录流指针 
          返回值:
            成功返回目录项指针
            失败返回NULL 
            读到末尾返回NULL 
struct dirent {
                ino_t          d_ino;       /* Inode number */
                off_t          d_off;       /* Not an offset; see below */
                unsigned short d_reclen;    /* Length of this record */
                unsigned char  d_type;      /* Type of file; not supported
                                                by all filesystem types */
                char           d_name[256]; /* Null-terminated filename */
            };    

2.3.关闭目录

        closedir

 int closedir(DIR *dirp);
          功能:
            关闭目录流指针 
          参数:
            dirp:目录流指针
          返回值:
            成功返回0 
            失败返回-1 

2.4.实例 

        实例1.读取某个目录

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

int SearchDir(char *file)
{
    DIR *p = NULL;
    struct dirent *pp =NULL;
    

    p = opendir(file);
    if(p == NULL)
    {
        perror("");
        return -1;
    }

    while(1)
    {
        pp = readdir(p);
        if(pp == NULL)
        {
            break;
        }

        if(*pp->d_name == '.')
        {
            continue;
        }
        printf("%s/%s\n", file,pp->d_name);
    }
    closedir(p);

    return 0;
}
int main(void)
{
    char filename[128] = {0};
    int ret = 0;

    printf("请输入文件路径:");
    scanf("%s", filename);

    ret = SearchDir(filename);
    if(ret == 0)
    {
        printf("success!\n");
    }
    else
    {
        printf("failed!\n");
    }


    return 0;
}

        2.读取某个目录下以及子目录下的所有目录,并打印查询时间

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


int SearchDir(char *file)
{
    DIR *p = NULL;
    struct dirent *pp =NULL;
    char filepath[1024] = {0};
    

    p = opendir(file);
    if(p == NULL)
    {
        perror("");
        return -1;
    }

    while(1)
    {
        pp = readdir(p);
        if(pp == NULL)
        {
            break;
        }

        if(*pp->d_name == '.')
        {
            continue;
        }
        sprintf(filepath,"%s/%s", file, pp->d_name);
        
        printf("%s\n", filepath);
        
        if(pp->d_type == DT_DIR)
        {
            SearchDir(filepath);
        }

    }
    
    closedir(p);

    return 0;
}
int main(void)
{
    char filename[128] = {0};
    int ret = 0;
    struct timeval start;
    struct timeval end;
    time_t t1;
    time_t t2;
    time_t ts;

    printf("请输入文件路径:");
    scanf("%s", filename);

    time(&t1);
    gettimeofday(&start, NULL);
    ret = SearchDir(filename);
    gettimeofday(&end, NULL);
    time(&t2);

    ts=(end.tv_sec*1000000+end.tv_usec) - (start.tv_sec*1000000+start.tv_usec);

    printf("%02ld:%02ld:%02ld\n", (t2-t1)/3600, (t2-t1)%3600/60, (t2-t1)%60);

    printf("耗时 %ld.%ld s\n", ts / 1000000, ts % 1000000);

    if(ret == 0)
    {
        printf("success!\n");
    }
    else
    {
        printf("failed!\n");
    }


    return 0;
}

三、链接文件接口 

3.1.软链接

        1.在终端

                命令:ln -s  file.txt   a.txt

        2.软件编程中

 int symlink(const char *target, const char *linkpath);
    功能:
        创建一个linkpath的软连接文件,里面存放target字符串
    参数:
        target:链接向的文件名
        linkpath:软链接文件名
    返回值:
        成功返回0 
        失败返回-1 
ssize_t readlink(const char *restrict path, char *restrict buf, size_t bufsize);
    功能: 
        读取软链接文件本身内容
    参数:
        path:软链接文件名 
        buf:存放软链接文件内容的缓冲区 
        bufsize:缓冲区的大小 
    返回值:
        成功返回读取的字节数 
        失败返回-1

        3.注意点

                软链接,通过文件名链接。如果删除了源文件,则连接文件则无法使用。 

                软连接文件名 -> inode -> 数据块 -> 链接向的文件名 -> inode -> 数据块 

 3.2.硬链接

        1.在终端

                命令:ln   file.txt   a.txt

        2.在软件编程中 

        int link(const char *oldpath, const char *newpath);
        功能:
            创建一个newpath的硬链接文件
        参数:
            oldpath:要链接的文件名
            newpath:硬链接文件名
        返回值:
            成功返回0 
            失败返回-1 
int unlink(const char *pathname);
        功能:
            删除链接文件名,并让硬链接个数-1 ,如果一个磁盘空间硬链接个数为0,需要回收磁盘空间
        参数:
            pathname:链接文件名
        返回值:
            成功返回0
            失败返回-1 

 3.注意点

        硬链接是通过inode序列链接的,链接文件与源文件使用相同的inode,因此在删除链接文件时,删除那个都不会影响另一个,另一个会成为一个独立的文件。

 3.3.实例

        1.软链接

                创建软链接,并打印,连接文件的内容和连接文件内部的内容

#include <stdio.h>
#include <unistd.h>
#include <string.h>


int main(void)
{
    FILE *fp = NULL;
    char tmpbuff[4096] = {0};

    symlink("file.txt", "a.txt");

    fp = fopen("a.txt", "r");
    if (NULL == fp)
    {
        perror("fail to fopen");
        return -1;
    }

    fgets(tmpbuff, sizeof(tmpbuff), fp);
    printf("%s\n", tmpbuff);

    fclose(fp);

    memset(tmpbuff, 0, sizeof(tmpbuff));
    readlink("a.txt", tmpbuff, sizeof(tmpbuff));
    printf("连接文件本身的数据:%s\n", tmpbuff);
    
    return 0;
}

 

        2.硬链接 

         建立链接,删除链接操作

#include <stdio.h>
#include <unistd.h>


int main(void)
{
    FILE *fp = NULL;
    fp = fopen("file.txt","w");
    
    link("file.txt","a.txt");
    unlink("file.txt");

    return 0;
}

    

四、文件详细接口

4.1.stat和lstat

int lstat(const char *pathname, struct stat *statbuf);
  功能:
    获得pathname对应文件的详细信息 
  参数:
    pathname:文件路径
    statbuf:存放文件详细信息空间的首地址
  返回值:
    成功返回0 
    失败返回-1 
 struct stat {
        dev_t     st_dev;         /* ID of device containing file */
        ino_t     st_ino;         /* Inode number */
        mode_t    st_mode;        /* File type and mode */
        nlink_t   st_nlink;       /* Number of hard links */
        uid_t     st_uid;         /* User ID of owner */
        gid_t     st_gid;         /* Group ID of owner */
        dev_t     st_rdev;        /* Device ID (if special file) */
        off_t     st_size;        /* Total size, in bytes */
        blksize_t st_blksize;     /* Block size for filesystem I/O */
        blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

        /* Since Linux 2.6, the kernel supports nanosecond
            precision for the following timestamp fields.
            For the details before Linux 2.6, see NOTES. */

        struct timespec st_atim;  /* Time of last access */
        struct timespec st_mtim;  /* Time of last modification */
        struct timespec st_ctim;  /* Time of last status change */

    #define st_atime st_atim.tv_sec      /* Backward compatibility */
    #define st_mtime st_mtim.tv_sec
    #define st_ctime st_ctim.tv_sec
    };

4.2.实例

        使用lstat获取一个文件的详细信息,文件类型,链接数、拥有者、同组者、文件大小、创建时间、文件名

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

int DisplayFile(char *pfilepath)
{
    struct stat buf;
    int ret = 0;

    ret = lstat(pfilepath, &buf);
    if (-1 == ret)
    {
        return -1;
    }

    switch (buf.st_mode & S_IFMT)
    {
        case S_IFREG:putchar('-');break;
        case S_IFSOCK:putchar('s');break;
        case S_IFLNK:putchar('l');break;
        case S_IFBLK:putchar('b');break;
        case S_IFDIR:putchar('d');break;
        case S_IFCHR:putchar('c');break;
        case S_IFIFO:putchar('p');break;
    }
    putchar(' ');

    printf("%ld ", buf.st_nlink);
    printf("%d ", buf.st_uid);
    printf("%d ", buf.st_gid);
    printf("%ld ", buf.st_size);
    printf("%ld ", buf.st_mtime);
    printf("%s\n", pfilepath);

    return 0;
}

int main(void)
{
    char filepath[256] = {0};

    printf("请输入文件路径:\n");
    scanf("%s", filepath);

    DisplayFile(filepath);

    return 0;
}

五、总结

        目录文件IO操作对象是目录,可以获取目录下的文件信息。连接文件IO,区别软连接和硬链接。文件详情IOlstat,也就是可以与目录文件IO配合可以实现ls-l的shell命令功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值