-2
我正在通过参数获取文件并返回其信息和名称的程序。我得到错误错误的文件描述。我的代码如下所示:错误的文件描述符C
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
int main(int argc, char *argv[]){
if(argc < 2){
printf("Error");
return 1;
}
else
{
int i;
for(i=1;i<argc;i++)
{
int file = 0;
file = open(argv[i], O_RDONLY);
if(file == -1)
{
close(file);
return 1;
}
else
{
struct stat info;
if(fstat(file, &info) < 0)
{
close(file);
return 1;
}
else
{
printf("Status information for %s\n",argv[i]);
printf("Size of file: %d \n", info.st_size);
printf("Number of connections: %d\n", info.st_nlink);
printf("inode: %d\n", info.st_ino);
printf("Last used : %s", ctime(&info.st_atime));
printf("Last change : %s", ctime(&info.st_mtime));
printf("Last status of change : %s", ctime(&info.st_ctime));
printf("ID owner : %d\n", info.st_uid);
printf("ID group : %d\n", info.st_gid);
printf("ID device : %d\n", info.st_dev);
printf("Security : :");
printf((S_ISDIR(info.st_mode)) ? "d" : "-");
printf((info.st_mode & S_IRUSR) ? "r" : "-");
printf((info.st_mode & S_IWUSR) ? "w" : "-");
printf((info.st_mode & S_IXUSR) ? "x" : "-");
printf((info.st_mode & S_IRGRP) ? "r" : "-");
printf((info.st_mode & S_IWGRP) ? "w" : "-");
printf((info.st_mode & S_IXGRP) ? "x" : "-");
printf((info.st_mode & S_IROTH) ? "r" : "-");
printf((info.st_mode & S_IWOTH) ? "w" : "-");
printf((info.st_mode & S_IXOTH) ? "x" : "-");
if(S_ISREG(info.st_mode)){
printf("\nFile is regular\n");
}
else if(S_ISDIR(info.st_mode)){
printf("\nFile is a directory\n");
}
printf("\n===================================\n");
close(file);
}
}
}
}
return 0;
}
当我运行这样的程序,例如: ./program somefile 我得到这个回报 - >错误的文件描述符
尝试来这里之前先google搜索,有吨answeres在那里 – redFIVE
如果'open'失败,为什么你会尝试'close'结果呢?它仅在错误时返回-1,因为_can't_不是有效的文件描述符,所以_cannot_对'close'有效。 – Useless
你从哪里看到这个错误? –