错误的文件描述符C
问题描述:
我正在通过参数获取文件并返回其信息和名称的程序。我得到错误错误的文件描述。我的代码如下所示:错误的文件描述符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 我得到这个回报 - >错误的文件描述符
答
的问题是在这里:
file = open(argv[i], O_RDONLY);
if(file == -1)
{
close(file);
return 1;
}
因为当file==-1
,它不是一个有效的文件描述符传递给close
。
可以安抚自己,这是确定不叫close
在这个分支,因为如果open
失败,有是没什么close
摆在首位。
顺便说一句,close
也有一个返回值,都open
和close
设置errno
如果他们失败:您可以检查,并记录,所有这些。事实上,几乎所有的代码最终都是错误检查/处理,这是其他语言(如C++)引入异常的动机之一。
int file = open(argv[i], O_RDONLY);
if(file == -1) {
perror("open failed");
return 1;
}
struct stat info;
if (fstat(file, &info) < 0) {
perror("fstat failed");
if (close(file) < 0) {
perror("close failed");
}
return 1;
}
尝试来这里之前先google搜索,有吨answeres在那里 – redFIVE
如果'open'失败,为什么你会尝试'close'结果呢?它仅在错误时返回-1,因为_can't_不是有效的文件描述符,所以_cannot_对'close'有效。 – Useless
你从哪里看到这个错误? –