我以前从未见过:
上面的左下角是什么?该程序的最新版本是
#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:~$