gpt4 book ai didi

c - 判断open()函数打开的是文件还是目录?

转载 作者:太空宇宙 更新时间:2023-11-04 06:00:55 26 4
gpt4 key购买 nike

我想用 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() 函数是否打开了文件或目录?

最佳答案

使用 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;

}

关于c - 判断open()函数打开的是文件还是目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19477645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com