I call nftw()
function like this:
nftw("/sys/class/tty", opearate_on_tty_item, 1, flags)
and function nftw()
executes function operate_on_tty_item()
for every item that it finds in the folder /sys/class/tty
.
Function operate_on_tty_item()
gets argumments directly from nftw()
and it checks if current /sys/class/tty/<device>
device has subfolder device/driver
(this means it is a physical device) and prints this device in a slightly different format i.e. /dev/<device>
. The function itself looks like this:
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("%s
", directory_concatenation);
}
// Close the opened directory.
closedir(directory);
// Reset concatenated string to null string.
directory_concatenation[0] = '';
return 0;
}
The thing I don't understand here is the line:
strcat(directory_concatenation, path + ftw_structure->base);
This line summs const char * path
and ftw_structure->base
. But the printf()
that follows
printf("%s
", directory_concatenation);
prins a string (for example /dev/ttyUSB0
)! How is this possible? How is this string created using the sum operation of a constant character pointer and an integer?
I am completely confused because FTW member FTW.base is defined in POSIX header ftw.h
like this (it is an integer):
/* Structure used for fourth argument to callback function for `nftw'. */
struct FTW
{
int base;
int level;
};
So how does POSIX compliant system know to display the string? How is this even calculated?
question from:
https://stackoverflow.com/questions/66061824/how-can-sum-of-ftw-base-and-some-string-path-returns-a-string 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…