错误的文件描述符C
我正在编写一个程序,该程序通过参数获取文件并返回其信息和名称。Im获取错误错误文件描述。我的代码如下所示:错误的文件描述符C,c,C,我正在编写一个程序,该程序通过参数获取文件并返回其信息和名称。Im获取错误错误文件描述。我的代码如下所示: #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
#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[]){
如果(argc<2){
printf(“错误”);
返回1;
}
其他的
{
int i;
对于(i=1;i坏文件描述符),问题在于:
file = open(argv[i], O_RDONLY);
if(file == -1)
{
close(file);
return 1;
}
因为,当file==-1
时,传递给close
的文件描述符无效
您可以放心,在这个分支中不调用close
是可以的,因为如果open
失败,那么首先就没有什么可以close
另一方面,close
也有一个返回值,open
和close
seterrno
如果失败:您可以检查并记录所有这些。几乎所有代码最终都是错误检查/处理,这是其他语言(如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;
}
int file=open(argv[i],仅限ordu);
如果(文件==-1){
perror(“开放式失败”);
返回1;
}
结构统计信息;
if(fstat(文件和信息)<0){
perror(“fstat失败”);
如果(关闭(文件)<0){
perror(“关闭失败”);
}
返回1;
}
来这里之前先用谷歌搜索一下,有很多答案如果打开
失败,你为什么要尝试关闭
结果?错误时它只会返回-1,因为这不是有效的文件描述符,因此不能有效地关闭
。你在哪里看到这个错误?这就是问题所在