我这样调用nftw()
函数:
nftw("/sys/class/tty", opearate_on_tty_item, 1, flags)
和函数nftw()
对它在文件夹/sys/class/tty
中找到的每个项执行函数operate_on_tty_item()
。
函数operate_on_tty_item()
直接从nftw()
获取参数,它检查当前/sys/class/tty/<device>
设备是否有子文件夹device/driver
(这意味着它是一个物理设备),并以稍微不同的格式打印该设备,即/dev/<device>
。函数本身看起来像这样:
static int opearate_on_tty_item(const char *path, const struct stat *buffer, int flags, struct FTW *ftw_structure)
{
max_sub_directories = 1;
// If depth is higher than max_sub_directories, ignore this field and advance to the next file.
if (ftw_structure->level > max_sub_directories) {
// Tell nftw() to continue and take next item.
return 0;
}
// Concatenate string of the object's path, to which we append "/device/driver".
strcat(directory_concatenation, path);
strcat(directory_concatenation, "/device/driver");
// Open the directory stored in concatenated string and check if it exists
if ((directory = opendir(directory_concatenation))) {
// Reset concatenated string to null string.
directory_concatenation[0] = ' ';
// Concatenate string.
strcat(directory_concatenation, "/dev/");
strcat(directory_concatenation, path + ftw_structure->base);
printf("%sn", directory_concatenation);
}
// Close the opened directory.
closedir(directory);
// Reset concatenated string to null string.
directory_concatenation[0] = ' ';
return 0;
}
我不明白的是这一行:
strcat(directory_concatenation, path + ftw_structure->base);
这一行是const char * path
和ftw_structure->base
的总和。但是
printf()
printf("%sn", directory_concatenation);
打印字符串(例如/dev/ttyUSB0
)!这怎么可能呢?如何使用一个常量字符指针和一个整数的和操作创建这个字符串?
我完全困惑,因为FTW成员FTW。base在POSIX头文件ftw.h
中定义如下(它是一个整数):
/* Structure used for fourth argument to callback function for `nftw'. */
struct FTW
{
int base;
int level;
};
那么POSIX兼容系统如何知道显示字符串呢?这是怎么计算出来的?
这怎么可能?
似乎directory_concatenation
是一个指针,指向包含/dev/ttyUSB0
的内存,后面跟着一个零字节。
如何使用一个常量字符指针和一个整数的和操作创建这个字符串?
将整型值加到指针存储的地址中,使指针值自增。因为从文档中:
nftw()在调用fn()时提供的第四个参数是aFTW型结构:
struct FTW { int base; int level; };
base是文件名(即basename组件)的偏移量
fpath
给出的路径名。[…]
计算的结果是一个指向字符串的指针,该字符串表示路径的文件名。然后strcat
在directory_concatenation
指针指向的内存中找到第一个零字节,复制表示文件名的字节,一个字节接一个字节地从directory_concatenation
指向的内存中的零字节位置开始。后面的零字节也被复制,从而创建一个新的字符串,将filename的值连接到前一个字符串。