Reading catalog

I am trying to solve the exercises from K & R; it's about reading directories. This task is system dependent because it uses system calls. In the book’s example, the authors say that their example was written for version 7 and System V UNIX systems and that they used the directory information in the <sys / dir.h> header, which looks like this:

#ifndef DIRSIZ
#define DIRSIZ 14
#endif
struct direct {    /* directory entry */
    ino_t d_ino;           /* inode number */
    char d_name[DIRSIZ];   /* long name does not have '\0' */
};

On this system, they use "struct direct" in combination with the "read" function to retrieve a directory entry that consists of a file name and an inode number.

.....
struct direct dirbuf;    /* local directory structure */
while(read(dp->fd, (char *) &dirbuf, sizeof(dirbuf)
               == sizeof(dirbuf) {
    .....
}
.....

I believe this works fine on UNIX and Linux systems, but I want to change this to work on Windows XP.

- Windows, , struct direct, "read" , , ?

, , Windows ?

+3
4
+2

, Linux/Unix. , , Cygwin Windows, Unix API.

+1

boost::filesystem::directory_iterator API FindFirstFile/FindNextFile Windows API- POSIX readdir_r(). . .

, ++ C.

+1

, K & R 1st Edition, 1978 , . .. .

Unix- . Unix , 14- , . , MacOS X (10.6.2) Solaris (10) Linux (SuSE Linux Enterprise Edition 10, ​​2.6.16.60-0.21-smp). :

read failed: (21: Is a directory)

POSIX , , , . , "fchdir()" , , , .

, opendir() , readdir() .. K & R raw open() read() ..

, , 30 , .


Windows POSIX , Cygwin MingW, opendir() readdir(), open() read() .

Or you can use the native Windows API that BillyONeal refers to, FindFirstFile and relatives.


Test code:

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
    int fd = open(".", O_RDONLY);
    if (fd != -1)
    {
        char buffer[256];
        ssize_t n = read(fd, buffer, sizeof(buffer));
        if (n < 0)
        {
            int errnum = errno;
            printf("read failed: (%d: %s)\n", errnum, strerror(errnum));
        }
        else
            printf("read OK: %d bytes (%s)\n", (int)n, buffer);
        close(fd);
    }
    return(0);
}
+1
source

Source: https://habr.com/ru/post/1737843/


All Articles