我以前从未见过这样的情况:

上面的左下角是什么?该程序的最新版本是
#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:~$ 发布于 2013-03-07 04:03:21
这很可能是因为没有将有效的const char*传递给void perror(const char *s),这会使<filename>: No such file or directory输出中的文件名成为垃圾/不可打印字符。
perror()函数应将通过符号errno访问的错误号映射到语言相关的错误消息,该消息应写入标准错误流,如下所示:
首先(如果s不是空指针,并且s所指向的字符也不是空字节),返回s后跟冒号和a所指向的字符串。
然后是错误消息字符串,后跟一个.
发布于 2013-03-07 04:07:33
我认为您更正了警告driveinfo.c:17或发布了您的代码。它是OK的;)
祝你好运!
发布于 2013-03-07 04:13:24
“涂上一层清漆,用它来打磨……”听起来像是用非字符串的东西调用perror?
如果你张贴代码,我们可能会看得更清楚,但我很确定警告和输出是相关的。
编辑:如果你将filename[25]传递给函数,我会看到这个警告。如果您传递的是&filename[25],那么您可能会传入根本不是字符串的内容,因此会打印一些随机字节,这几乎可以打印任何内容。
https://stackoverflow.com/questions/15256841
复制相似问题