您好,欢迎来到筏尚旅游网。
搜索
您的当前位置:首页linux文件夹操作

linux文件夹操作

来源:筏尚旅游网

文件夹操作步骤:

获取文件夹路径
  1. 直接给出一个字符串
  2. 获取当前文件夹路径,去找相对路径
//获取当前工作路径
char *getcwd(char *buffer, size_t size);
					成功:返回 指向 buffer 的指针; 失败:返回 NULL
打开文件夹
DIR *opendir(char *dir_path);
				 成功:返回指针;失败:返回NULL
操作文件

一般情况下需要在程序执行过程中操作的文件都是配置文件,所以内容简单、固定。

//读取文件夹里文件
struct dirent *readdir(DIR *dirp);
			成功:返回指针;读到文件夹末尾 或 失败:返回 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 */
	};

//获取文件详细属性
int stat(const char *pathname, struct stat *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
	};

关闭文件
int closedir(DIR *dirp);
				成功:返回 0; 失败:返回 -1

文件夹流定位

//将文件夹指针定位到开头
void rewinddir(DIR *dir);

//得到当前文件夹流指针的位置
long telldir(DIR *dirp);
			成功:返回 当前文件夹流指针的位置
			
//设置文件夹流的位置
void seekdir(DIR *dirp, long loc);  // 参数 loc 是 距离开头的绝对值, 可以用 telldir的返回值来计算距离当前位置的相对值

------ 参考《UNIX环境高级编程(第三版)》
------ 参考 《 Manual pager utils》(linux man 手册)

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- efsc.cn 版权所有 赣ICP备2024042792号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务