您的位置:首页 > 运维架构 > Linux

Linux下的目录操作

2015-09-20 13:34 549 查看
环境:Vmware Workstation;CentOS-6.4-x86_64

说明:

1、目录操作第一步:打开目录,用opendir函数打开目录文件。

2、目录操作第二步:读取目录,用readdir函数读出目录文件内容。

3、目录操作第三步:关闭目录,用closedir函数关闭目录文件。

函数说明:

DIR *opendir(const char *pathname);

struct dirent *readdir(DIR *dir);

int closedir(DIR *dir);

Opendir函数打开pathname指向的目录文件,如果错误返NULL

程序图解说明:



步骤:

1、创建并编写源文件main.c:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char *args[])
{
// 判断用户输入的参数是否符合要求
if (argc < 2)
{
printf("Message : Please input more arguments.\n");
return -1;
}

// 获取用户输入的参数
const char *temp_dir = args[1];
// 打开目录,如果打开目录失败,返回NULL,成功返回目录结构体
DIR *dir = opendir(temp_dir);
// 判断目录是否正确打开
if (dir == NULL)
{
printf("Message : directory open failed, %s\n", strerror(errno));
}
// 定义结构体指针,用来获取readdir的返回值
struct dirent *dest;
// 循环读取目录
while (1)
{
// 读取目录
// readdir返回的是指向文件的指针
// 如果读取失败,返回NULL并设置errno
// 如果到目录的结束,返回NULL,不设置errno
dest = readdir(dir);
if (dest == NULL)
{
return 0;
}
else
{
printf("filename : %s\n", dest->d_name);
}
}

// 关闭目录
closedir(dir);
return 0;
}
2、创建并编写文件makefile:

.SUFFIXES:.c .o

CC=gcc

SRCS=main.c
OBJS=$(SRCS:.c=.o)
EXEC=main

start: $(OBJS)
$(CC) -o $(EXEC) $(OBJS)
@echo "-----------------------------OK-----------------------"

.c.o:
$(CC) -Wall -o $@ -c $<

clean:
rm -rf $(EXEC) $(OBJS)
3、编译并执行程序:

[negivup@negivup mycode]$ make
gcc -Wall -o main.o -c main.c
gcc -o main main.o
-----------------------------OK-----------------------
[negivup@negivup mycode]$ ./main /  这是执行程序时输入的形式
................

PS:根据传智播客视频学习整理得出。

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: