我像这样调用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] = '\0';
// Concatenate string.
strcat(directory_concatenation, "/dev/");
strcat(directory_concatenation, path + ftw_structure->base);
printf("%s\n", directory_concatenation);
}
// Close the opened directory.
closedir(directory);
// Reset concatenated string to null string.
directory_concatenation[0] = '\0';
return 0;
}我不明白的是这句话:
strcat(directory_concatenation, path + ftw_structure->base);这一行是const char * path和ftw_structure->base的总和。但是接下来的printf()
printf("%s\n", 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兼容的系统如何知道如何显示字符串呢?这是怎么计算出来的?
发布于 2021-02-05 12:33:34
,这怎么可能?
directory_concatenation似乎是一个指针,指向一个内存,其中包含/dev/ttyUSB0,后面是一个零字节。
如何使用常量字符指针和整数的求和操作创建这个字符串?
整数的值被添加到指针存储的地址中,从而增加指针值。因为从文件中:
调用fn()时nftw()提供的第四个参数是FTW类型的结构:
结构FTW { int基;int级;};
base是fpath中给定的路径名中文件名(即basename组件)的偏移量。..。
计算的结果是指向表示路径文件名的字符串的指针。然后strcat在directory_concatenation指针指向的内存中找到第一个零字节,将表示该文件名的字节依次复制到从directory_concatenation指向的内存中的零字节位置开始。尾随的零字节也会被复制,从而创建一个新的字符串,并将文件名的值连接到前一个字符串。
https://stackoverflow.com/questions/66061824
复制相似问题