ALPHASORT(3POSIX)

✨ ALPHASORT(3POSIX) β€” alphasort, scandir: scan a directory ✨

okay so bestie, welcome to the POSIX Programmer's Manual πŸ’– this page is literally the whole vibe for alphasort() and scandir(), and we're gonna go through it together, no skipping, no gatekeeping.

Quick heads up before we dive in 🫢 This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (so pls consult the corresponding Linux manual page for the actual Linux behavior deets), or honestly the interface may not be implemented on Linux at all. Not me warning you first thing, but it had to be said. πŸ’€

🌸 PROLOG 🌸

This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.


πŸ¦‹ NAME πŸ¦‹

alphasort, scandir β€” scan a directory. That's the whole job. Iconic. πŸ‘‘


πŸ’… SYNOPSIS πŸ’…

#include <dirent.h>

int alphasort(const struct dirent **d1, const struct dirent **d2);
int scandir(const char *dir, struct dirent ***namelist,
    int (*sel)(const struct dirent *),
    int (*compar)(const struct dirent **, const struct dirent **));

like look at those signatures. chefs kiss. πŸ’–


✨ DESCRIPTION ✨

So alphasort() is the comparison-function bestie you hand to scandir() when you want the directory entries d1 and d2 sorted into alphabetical order. The sorting happens as if by calling the strcoll() function on the d_name element of the dirent structures you passed as the two parameters. And if strcoll() fails? Then the return value of alphasort() is unspecified β€” no cap, we just don't know. πŸ™ˆ

Also, important: alphasort() shall not change the setting of errno if it's successful. And since there is no return value reserved to indicate an error, if your application wants to check for error situations, you should set errno to 0, then call alphasort(), then check errno. That's the move. Set it, call it, check it. periodt.

Now for scandir() πŸ‘‘ β€” it shall scan the directory dir, calling the function referenced by sel on each directory entry. Entries for which the function referenced by sel returns non-zero shall be stored in strings allocated as if by a call to malloc(), and sorted as if by a call to qsort() with the comparison function compar, except that compar need not provide total ordering. The strings are collected in array namelist, which shall be allocated as if by a call to malloc(). If sel is a null pointer, all entries shall be selected β€” everything gets an invite to the party πŸŽ‰. And if the comparison function compar does not provide total ordering, then the order in which the directory entries are stored is unspecified. it's giving chaos, lowkey.


🌈 RETURN VALUE 🌈

Upon successful completion, alphasort() shall return an integer greater than, equal to, or less than 0, according to whether the name of the directory entry pointed to by d1 is lexically greater than, equal to, or less than the directory pointed to by d2 β€” when both are interpreted as appropriate to the current locale. And there is no return value reserved to indicate an error. So don't go looking for one, bestie, it's not there. 🫢

Upon successful completion, scandir() shall return the number of entries in the array, and a pointer to the array through the parameter namelist. Otherwise, scandir() shall return -1. 😭


πŸ”₯ ERRORS πŸ”₯

The scandir() function shall fail if:

  • EACCES β€” Search permission is denied for the component of the path prefix of dir, or read permission is denied for dir. (the audacity.)
  • ELOOP β€” A loop exists in symbolic links encountered during resolution of the dir argument. round and round we go πŸŒ€
  • ENAMETOOLONG β€” The length of a component of a pathname is longer than {NAME_MAX}.
  • ENOENT β€” A component of dir does not name an existing directory, or dir is an empty string. (empty string? in this economy?)
  • ENOMEM β€” Insufficient storage space is available. 😭
  • ENOTDIR β€” A component of dir names an existing file that is neither a directory nor a symbolic link to a directory.
  • EOVERFLOW β€” One of the values to be returned or passed to a callback function cannot be represented correctly.

The scandir() function may fail if:

  • ELOOP β€” More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the dir argument.
  • EMFILE β€” All file descriptors available to the process are currently open. (close some tabs, bestie πŸ’€)
  • ENAMETOOLONG β€” The length of a pathname exceeds {PATH_MAX}, or pathname resolution of a symbolic link produced an intermediate result with a length that exceeds {PATH_MAX}.
  • ENFILE β€” Too many files are currently open in the system.

The following sections are informative.


πŸŽ€ EXAMPLES πŸŽ€

Here's an example to print the files in the current directory β€” literally the cutest little snippet:

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
...
struct dirent **namelist;
int i,n;

    n = scandir(".", &namelist, 0, alphasort);
    if (n < 0)
        perror("scandir");
    else {
        for (i = 0; i < n; i++) {
            printf("%s\n", namelist[i]->d_name);
            free(namelist[i]);
            }
        }
    free(namelist);
...

look at her go ✨


πŸ’œ APPLICATION USAGE πŸ’œ

If dir contains filenames that do not form character strings, or which contain characters outside the domain of the collating sequence of the current locale, then alphasort() need not provide a total ordering. This condition is not possible if all filenames within the directory consist only of characters from the portable filename character set. so like, keep it portable and you're golden πŸ’…

The scandir() function may allocate dynamic storage during its operation. And if scandir() is forcibly terminated β€” like by longjmp() or siglongjmp() being executed by the function pointed to by sel or compar, or by an interrupt routine β€” then scandir() does not have a chance to free that storage, so it remains permanently allocated. 😭 A safe way to handle interrupts is to store the fact that an interrupt has occurred, then wait until scandir() returns to act on the interrupt. patience is a virtue, fr fr.

For functions that allocate memory as if by malloc(), the application should release such memory when it is no longer required by a call to free(). For scandir(), this is namelist β€” including all of the individual strings in namelist. don't forget the little ones, they matter too πŸ₯Ί


🧚 RATIONALE 🧚

None.


⭐ FUTURE DIRECTIONS ⭐

None.


🌸 SEE ALSO 🌸

  • qsort()
  • strcoll()

The Base Definitions volume of POSIX.1‐2017, <dirent.h>


Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .

Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .


and that's the whole page bestie, you ate that πŸ’… this one came to you from IEEE/The Open Group, 2017 β€” thanks for reading, mwah πŸ«ΆπŸ’–