Blame manual/examples/mkdirent.c

Packit 6c4009
/* Example for creating a struct dirent object for use with glob.
Packit 6c4009
   Copyright (C) 2016-2018 Free Software Foundation, Inc.
Packit 6c4009
Packit 6c4009
   This program is free software; you can redistribute it and/or
Packit 6c4009
   modify it under the terms of the GNU General Public License
Packit 6c4009
   as published by the Free Software Foundation; either version 2
Packit 6c4009
   of the License, or (at your option) any later version.
Packit 6c4009
Packit 6c4009
   This program is distributed in the hope that it will be useful,
Packit 6c4009
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 6c4009
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 6c4009
   GNU General Public License for more details.
Packit 6c4009
Packit 6c4009
   You should have received a copy of the GNU General Public License
Packit 6c4009
   along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
Packit 6c4009
*/
Packit 6c4009
Packit 6c4009
#include <dirent.h>
Packit 6c4009
#include <errno.h>
Packit 6c4009
#include <stddef.h>
Packit 6c4009
#include <stdlib.h>
Packit 6c4009
#include <string.h>
Packit 6c4009
Packit 6c4009
struct dirent *
Packit 6c4009
mkdirent (const char *name)
Packit 6c4009
{
Packit 6c4009
  size_t dirent_size = offsetof (struct dirent, d_name) + 1;
Packit 6c4009
  size_t name_length = strlen (name);
Packit 6c4009
  size_t total_size = dirent_size + name_length;
Packit 6c4009
  if (total_size < dirent_size)
Packit 6c4009
    {
Packit 6c4009
      errno = ENOMEM;
Packit 6c4009
      return NULL;
Packit 6c4009
    }
Packit 6c4009
  struct dirent *result = malloc (total_size);
Packit 6c4009
  if (result == NULL)
Packit 6c4009
    return NULL;
Packit 6c4009
  result->d_type = DT_UNKNOWN;
Packit 6c4009
  result->d_ino = 1;            /* Do not skip this entry.  */
Packit 6c4009
  memcpy (result->d_name, name, name_length + 1);
Packit 6c4009
  return result;
Packit 6c4009
}