第六章 目录操作
#include <unistd.h>
char *getcwd(char *buff, size_t size);
ERANGE
char *buf;
int len = 50;
buf = malloc(len);
while (!getcwd(buf, len) && errno = ERANGE){
len += 50;
buf = realloc(buf, len);
}
get_current_dir_name(){
char *env = getenv(“PWD”);
if (env)
return strdup(env);
else
return getcwd(NULL, 0);
}
特殊文件.和..
int chdir(const char *pathname);
int fchdir(int fd);
int chroot(const char *path); chdir(“/”);
int mkdir(const char *dirname, mod_t mode);
int rmdir(char *pathname); ENOEMPTY
DIR *opendir(const char *pathname);
int closedir(DIR dir);
struct dirent *readdir(DIR *dir);
d_name, d_ino
例
#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
DIR *dir;
struct dirent *ent;
if (!(dir = opendir(".")))
{
perror("opendir");
return 1;
}
errno = 0;
while ((ent = readdir(dir)))
{
puts(ent->d_name);
errno = 0;
}
if (errno)
{
perror("readdir");
return 1;
}
closedir(dir);
return 0;
}
int rewinddir(DIR *dir);
文件名匹配
使用子进程
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, const char **argv)
{
char buf[1024];
FILE *file;
int result;
int i;
strcpy(buf, "ls ");
for (i = 1; i < argc; i++)
{
strcat(buf, argv[i]);
strcat(buf, " ");
}
file = popen(buf, "r");
if (!file)
{
perror("popen");
return 1;
}
while (fgets(buf, sizeof(buf),file))
{
printf("%s",buf);
}
result = pclose(file);
if (!WIFEXITED(result))
{
return 1;
}
return 0;
}
使用glob
int glob(const char *pattern, int flags, int errfunc(const char epath, int errno), glob_t *pglob);
? [] {} ~
typedef struct{
int gl_patch;
char **gl_pathv;
int gl_offs;
}glob_t
GLOB_ERR, GLOB_MARK, GLOB_NOSORT, GLOB_DOOFS, GLOB_NOCHECK,
GLOB_APPEND, GLOB_NOESCAPE, GLOB_PERIOD, GLOB_BRACE, GLOB_BRACE, GLOB_NOMAGIC, GLOB_TILDE, GLOB_ONLYDIR
int globerr(const char *pathname, int globerrno);
void globfree(glob_t *pglob);
GLOB_NOSPACE, GLOB_ABEND, GLOB_NOMATCH
#include <errno.h>
#include <glob.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int errfn(const char *pathname, int theerr)
{
fprintf(stderr, "error accessing %s:%s", pathname, strerror(theerr));
return 0;
}
int main(int argc, const char **argv)
{
glob_t result;
int i, rc, flags;
if (argc < 2)
{
printf("at least 1 arg/n");
return 1;
}
flags = 0;
for (i = 1;i < argc; i++)
{
rc = glob(argv[i], flags, errfn, &result);
if (rc == GLOB_NOSPACE)
{
fprintf(stderr, "out of space/n");
return 1;
}
flags |= GLOB_APPEND;
}
if(!result.gl_pathc)
{
fprintf(stderr, "no match/n");
rc = 1;
}
else
{
for (i = 0; i < result.gl_pathc; i++)
{
puts(result.gl_pathv[i]);
rc = 0;
}
}
globfree(&result);
return rc;
}