确定open()函数是否已打开文件或目录?

时间:2013-10-20 13:03:21

标签: c file

我想用read()函数读取一个文件,这是我的代码源:

char *buf;
    int bytesRead;
    int fildes;
    char path[128];
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
    int flags = O_RDONLY;
    printf("\n%s-->Donner l'emplacement du fichier :%s ", CYAN_NORMAL, RESETCOLOR);
    scanf("%s", path);
    fildes = open(path, flags, mode);
    if(fildes == -1){
        printf("\nImpossible de lire le fichier. Réessayez plus tard. (%s)",strerror(errno));
    }else{
        while ((bytesRead = read(fildes, buf, sizeof buf)) > 0)
        {
            write(STDOUT_FILENO, buf, bytesRead);
        }
    }

问题是当我将目录作为程序读取它的路径时,并显示一个空行,就像它是一个空文件一样。

我想只读取文件,当我将目录作为路径时,我希望我的程序显示一条消息。

我如何知道open()函数是否已打开文件或目录?

4 个答案:

答案 0 :(得分:2)

使用statfstat函数(第一个使用带有文件描述符的第二个函数)这里是执行该任务的函数:

    int isDir(char* path)
{
        struct stat buff;
        stat(path , &buff);
        if((buff.st_mode & S_IFMT) == S_IFDIR)
                return 0;
        else if ((buff.st_mode & S_IFMT) == S_IFREG)
                return 1;
        else
                return -1;

}

答案 1 :(得分:2)

您可以fstat路径并在尝试打开之前检查结构struct statst_mode属性,无论是目录还是文件。

示例:

int is_dir(const char* name)
{
    struct stat st;
    if (-1 == stat(name, &st)) {
      return -1; // check errno to see what went wrong
    }
    return (int)((st.st_mode & S_IFDIR) == S_IFDIR);
}

答案 2 :(得分:1)

您可以在打开前检查路径类型:

struct stat statbuf;
if( stat(path,&statbuf) == 0 )
{
    if (S_ISDIR(statbuf.st_mode) )
    {
        //it's a directory
    }
    else if (S_ISREG(statbuf.st_mode) )
    {
        //it's a file
    }
    else
    {
        //something else
    }
}

答案 3 :(得分:0)

Commeça:

fildes = open(path, flags, mode);
if(fildes == -1){
    printf("\nImpossible de lire le fichier. Réessayez plus tard. (%s)",strerror(errno));
}else{
    struct stat statb;

    if (fstat(fildes, &statb) == -1)
        printf("\nImpossible de «fstat» le fichier. Réessayez plus tard. (%s)",
            strerror(errno));
    else if ((statb.st_mode & S_IFMT) == S_IFDIR)
        printf("\nC'est un dossier, pas un fichier.");
    else
    {
        while ((bytesRead = read(fildes, buf, sizeof buf)) > 0)
        {
            write(STDOUT_FILENO, buf, bytesRead);
        }
    }
}

(随意修复我非常糟糕的法语;例如,我不知道“目录”的正确用语是什么。

fstat()可能比stat()快一点。

相关问题