gpt4 book ai didi

c - 为什么这个输出来自 perror?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:48:47 25 4
gpt4 key购买 nike

我以前从未见过:

enter image description here

上面的左下角是什么?该程序的最新版本是

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int ch;
char file_name[25] = "/proc/scsi/scsi";
FILE *fp;
fp = fopen(file_name,"r"); // read mode
if (fp == NULL)
{
perror(file_name);
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name);
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
return 0;
}

测试

$ cc driveinfo.c;./a.out 
The contents of /proc/scsi/scsi file are :
Attached devices:
Host: scsi0 Channel: 00 Id: 00 Lun: 00
Vendor: ATA Model: WDC WD2500JS-75N Rev: 10.0
Type: Direct-Access ANSI SCSI revision: 05
Host: scsi1 Channel: 00 Id: 00 Lun: 00
Vendor: ATA Model: ST3250824AS Rev: 3.AD
Type: Direct-Access ANSI SCSI revision: 05
Host: scsi2 Channel: 00 Id: 00 Lun: 00
Vendor: TSSTcorp Model: DVD+-RW TS-H653A Rev: D300
Type: CD-ROM ANSI SCSI revision: 05
Host: scsi3 Channel: 00 Id: 00 Lun: 00
Vendor: Optiarc Model: DVD-ROM DDU1681S Rev: 102A
Type: CD-ROM ANSI SCSI revision: 05
Host: scsi4 Channel: 00 Id: 00 Lun: 00
Vendor: Lexar Model: USB Flash Drive Rev: 1100
Type: Direct-Access ANSI SCSI revision: 00
Host: scsi5 Channel: 00 Id: 00 Lun: 00
Vendor: WD Model: 5000AAKB Externa Rev: l108
Type: Direct-Access ANSI SCSI revision: 00

以下重现了奇怪的输出:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int ch;
char file_name[25] = "/proc/scsi/scsi-notExist";
FILE *fp;
fp = fopen(file_name,"r"); // read mode
if (fp == NULL)
{
perror(&file_name[25]);
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name);
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
return 0;
}

更新

clang 编译器会发出警告但不会发出 (g)cc:

$ clang -Wconversion cpu-disk-info.c
cpu-disk-info.c:14:15: warning: array index of '25' indexes past the end of an
array (that contains 16 elements) [-Warray-bounds]
perror(&file_name[25]);
^ ~~
cpu-disk-info.c:6:4: note: array 'file_name' declared here
char file_name[] = "/proc/scsi/scsi";
^
1 warning generated.
dev@dev-OptiPlex-745:~$ gcc -Wconversion cpu-disk-info.c
dev@dev-OptiPlex-745:~$

最佳答案

这很可能是因为没有将有效的 const char* 传递给 void perror(const char *s) , 这使得文件名在 <filename>: No such file or directory 中输出为垃圾/不可打印字符。

The perror() function shall map the error number accessed through the symbol errno to a language-dependent error message, which shall be written to the standard error stream as follows:

First (if s is not a null pointer and the character pointed to by s is not the null byte), the string pointed to by s followed by a colon and a .

Then an error message string followed by a .

关于c - 为什么这个输出来自 perror?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15256841/

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