0% found this document useful (0 votes)
11K views

Linux

The document describes several file system functions in Linux - chmod() changes permissions of a file, chown() changes ownership, unlink() removes a link to a file, and link() creates a new link to an existing file. It provides the syntax, arguments, usage details, return values, errors, and examples for each function.

Uploaded by

Shaik Yusaf
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11K views

Linux

The document describes several file system functions in Linux - chmod() changes permissions of a file, chown() changes ownership, unlink() removes a link to a file, and link() creates a new link to an existing file. It provides the syntax, arguments, usage details, return values, errors, and examples for each function.

Uploaded by

Shaik Yusaf
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 31

File and directory Management:

chmod():
Change the permissions for a file

Synopsis:
#include <sys/types.h>

#include <sys/stat.h>

int chmod( const char * path, mode_t mode );

Arguments:
path
The name of the file whose permissions you want to change.
mode
The new permissions for the file. For more information, see
“Access permissions” in the documentation for stat().

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The chmod() function changes S_ISUID, S_ISGID, S_ISVTX and the file
permission bits of the file specified by the pathname pointed to by
path to the corresponding bits in the mode argument. The application
must ensure that the effective user ID of the process matches the
owner of the file or the process has appropriate privileges to do this.

If a directory is writable and the sticky bit (S_ISVTX) is set on the


directory, a process can remove or rename a file within that directory
only if one or more of the following is also true:

• The effective user ID of the process matches the file's owner ID.
• The effective user ID of the process matches the directory's
owner ID.
• The file is writable by the effective user ID of the process.
• The user is a superuser (effective user ID of 0).

If a directory has the set-group ID bit set, a file created in that


directory will have the same group ID as that directory. Otherwise, the
newly created file's group ID is set to the effective group ID of the
creating process.

1
If the calling process doesn't have appropriate privileges, and if
the group ID of the file doesn't match the effective group ID, and the
file is a regular file, bit S_ISGID (set-group-ID on execution) in the file's
mode is cleared on a successful return from chmod().

If the effective user ID of the calling process is equal to the file


owner, or the calling process has appropriate privileges (for example, it
belongs to the superuser), chmod() sets S_ISUID, S_ISGID and the file
permission bits, defined in the <sys/stat.h> header file, from the
corresponding bits in the mode argument.

These bits define access permissions for the user associated with
the file, the group associated with the file and all others. This call has
no effect on file descriptors for files that are already open.
If chmod() succeeds, the st_ctime field of the file is marked for update.
Returns:
0
Success.
-1
An error occurred (errno is set).

Errors:
EACCES
Search permission is denied on a component of the path prefix.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of the path string exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.
ENOTDIR
A component of the path prefix isn't a directory.
ENOENT
The file doesn't exist, or the path arguments points to an empty
string.
ENOSYS
The chmod() function isn't implemented for the filesystem
specified in path.
EPERM
The effective user ID doesn't match the owner of the file, and the
calling process doesn't have appropriate privileges.
EROFS
The file resides on a read-only filesystem.

2
Examples:
/*
* Change the permissions of a list of files
* to by read/write by the owner only
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
int main( int argc, char **argv )
{
int i;
int ecode = 0;
for( i = 1; i < argc; i++ ) {
if( chmod( argv[i], S_IRUSR | S_IWUSR ) == -1 ) {
perror( argv[i] );
ecode++;
} }
return ecode;
}
chown():
Change the user ID and group ID of a file

Synopsis:
#include <sys/types.h>

#include <unistd.h>

int chown( const char * path,uid_t owner, gid_t group );

3
Arguments:
path
The name of the file whose ownership you want to change.
owner
The user ID of the new owner.
group
The group ID of the new owner.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The chown() function changes the user ID and group ID of the file
specified by path to be the numeric values contained in owner and
group, respectively.

If the named file is a symbolic link, chown() changes the


ownership of the file or directory to which the symbolic link refers;
lchown() changes the ownership of the symbolic link file itself.

Only processes with an effective user ID equal to the user ID of


the file or with appropriate privileges (for example, the superuser) may
change the ownership of a file.
In QNX Neutrino, the _POSIX_CHOWN_RESTRICTED flag (tested
via the _PC_CHOWN_RESTRICTED flag in pathconf()), is enforced for
path. This means that only the superuser may change the ownership or
the group of a file to anyone. Normal users can't give a file away to
another user by changing the file ownership, nor to another group by
changing the group ownership.
If the path argument refers to a regular file, the set-user-ID (S_ISUID)
and set-group-ID (S_ISGID) bits of the file mode are cleared, if the
function is successful.

If chown() succeeds, the st_ctime field of the file is marked for


update.

Returns:
0 Success. -1 (no changes were made in the user ID and group ID of
the file).
An error occurred (errno is set).

Errors:
EACCES
Search permission is denied on a component of the path prefix.
ELOOP

4
Too many levels of symbolic links or prefixes.

ENAMETOOLONG
The length of the path string exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.
ENOENT
A component of the path prefix doesn't exist, or the path
arguments points to an empty string.
ENOSYS
The chown() function isn't implemented for the filesystem
specified in path.
ENOTDIR
A component of the path prefix isn't a directory.
EPERM
The effective user ID doesn't match the owner of the file, or the
calling process doesn't have appropriate privileges.
EROFS
The named file resides on a read-only filesystem.

Examples:
/*
* Change the ownership of a list of files
* to the current user/group */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main( int argc, char** argv )
{
int i;
int ecode = 0;
for( i = 1; i < argc; i++ ) {
if( chown( argv[i], getuid(), getgid() ) == -1 ) {
perror( argv[i] );
ecode++;
}
}

5
exit( ecode );
}

unlink():
Remove a link to a file

Synopsis:
#include <unistd.h>

int unlink( const char * path );

Arguments:
path
The name of the file that you want to unlink.

Library:
libc
Use the -l c option to qcc to link against this library. This library
is usually included automatically.

Description:
The unlink() function removes a link to a file:

• If the path names a symbolic link, unlink() removes the link, but
doesn't affect the file or directory that the link goes to.
• If the path isn't a symbolic link, unlink() removes the link and
decrements the link count of the file that the link refers to.

If the link count of the file becomes zero, and no process has the file
open, then the space that the file occupies is freed, and no one can
access the file anymore.
If one or more processes have the file open when the last link is
removed, the link is removed, but the removal of the file is delayed
until all references to it have been closed.

To remove a directory, call rmdir() or


remove().

Returns:
0
The operation was successful.
Nonzero
The operation failed (errno is set).

6
Errors:
EACCES
Search permission is denied for a component of path, or write
permission is denied on the directory containing the link to be
removed.
EBUSY
The directory named by path cannot be unlinked because it's
being used by the system or another process, and the target
filesystem or resource manager considers this to be an error.
ENAMETOOLONG
The path argument exceeds PATH_MAX in length, or a pathname
component is longer than NAME_MAX.
ENOENT
The named file doesn't exist, or path is an empty string.
ENOSYS
The unlink() function isn't implemented for the filesystem
specified by path.
ENOTDIR
A component of path isn't a directory.
EPERM
The file named by path is a directory, and either the calling
process doesn't have the appropriate privileges, or the target
filesystem or resource manager prohibits using unlink() on
directories.
EROFS
The directory entry to be unlinked resides on a read-only
filesystem.
Examples:
#include <unistd.h>

#include <stdlib.h>

int main( void )


{
if( unlink( "vm.tmp" ) )
{
puts( "Error removing vm.tmp!" );
return EXIT_FAILURE;
}

7
return EXIT_SUCCESS;
}

link():
Create a link to an existing file

Synopsis:
#include <unistd.h>

int link( const char* existing, const char* new );

Arguments:
existing
The path of an existing file.
new
The path for the new link.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The link() function creates a new directory entry named by new
to refer to (that is, to be a link to) an existing file named by existing.
The function atomically creates a new link for the existing file, and
increments the link count of the file by one.

This implementation doesn't support using link() on directories or the


linking of files across filesystems (different logical disks).

If the function fails, no link is created, and the link count of the file
remains unchanged.
If link() succeeds, the st_ctime field of the file and the st_ctime and
st_mtime fields of the directory that contains the new entry are
marked for update.

Returns:
0
Success.
-1
An error occurred (errno is set).

8
Errors:
EACCES
A component of either path prefix denies search permission, or
the link named by new is in a directory with a mode that denies
write permission.
EEXIST
The link named by new already exists.
ELOOP
Too many levels of symbolic links or prefixes.
EMLINK
The number of links to the file named by existing would exceed
LINK_MAX.
ENAMETOOLONG
The length of the existing or new string exceeds PATH_MAX, or a
pathname component is longer than NAME_MAX.
ENOENT
This error code can mean the following:

• A component of either path prefix doesn't exist.


• The file named by existing doesn't exist.
• Either existing or new points to an empty string.

ENOSPC
The directory that would contain the link can't be extended.

ENOSYS
The link() function isn't implemented for the filesystem specified
in existing or new.
ENOTDIR
A component of either path prefix isn't a directory.

EPERM
The file named by existing is a directory.
EROFS
The requested link requires writing in a directory on a read-only
file system.
EXDEV
The link named by new and the file named by existing are on
different logical disks.

Examples:
/*
* The following program performs a rename
* operation of argv[1] to argv[2].

9
* Please note that this example, unlike the
* library function rename(), ONLY works if
* argv[2] doesn't already exist.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main( int argc, char** argv )
{
/* Create a link of argv[1] to argv[2].
*/
if( link( argv[1], argv[2] ) == -1 ) {
perror( "link" );
return( EXIT_FAILURE );
}
if( unlink( argv[1] ) == -1 ) {
perror( argv[1] );
return( EXIT_FAILURE );
}
return( EXIT_SUCCESS );
}

symlink():
Create a symbolic link to a path

Synopsis:
#include <unistd.h>

int symlink( const char* pname, const char* slink );

Arguments:
pname
The path that you want to link to.
slink

10
The symbolic link that you want to create.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The symlink() function creates a symbolic link named slink that
contains the pathname specified by pname (slink is the name of the
symbolic link created, pname is the pathname contained in the
symbolic link).

File access checking isn't performed on the file named by


pname, and the file need not exist.
If the symlink() function is unsuccessful, any file named by slink is
unaffected.

Returns:
0 Success.
-1 An error occurred (errno is set).

Errors:
EACCES
A component of the slink path prefix denies search permission,
or write permission is denied in the parent directory of the
symbolic link to be created.
EEXIST
A file named by slink already exists.
ELOOP
A loop exists in symbolic links encountered during resolution of
the slink argument, and it resolves to more then SYMLOOP_MAX
levels.

ENAMETOOLONG
A component of the path specified by slink exceeds NAME_MAX
bytes, or the length of the entire pathname exceeded PATH_MAX
characters.
ENOSPC
The new symbolic link can't be created because there's no space
left on the filesystem that will contain the symbolic link.
ENOSYS
The symlink() function isn't implemented for the filesystem
specified in slink.
ENOTDIR
A component of the path prefix of slink isn't a directory.
EROFS

11
The file slink would reside on a read-only filesystem.

Examples:
/*

* create a symbolic link to "/usr/nto/include"

*/

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

int main( void )

if( symlink( "/usr/nto/include", "slink" ) == -1)

perror( "slink -> /usr/nto/include" );

exit( EXIT_FAILURE );

exit( EXIT_SUCCESS );

mkdir():
Create a subdirectory

Synopsis:
#include <sys/types.h>

#include <sys/stat.h>

int mkdir( const char *path,


mode_t mode );

Arguments:
path

12
The name of the directory that you want to create.
mode
The permissions for the directory, modified by the process's file-
creation mask (see umask()).
The access permissions for the file or directory are specified as a
combination of bits defined in the <sys/stat.h> header file. For
more information, see “Access permissions” in the
documentation for stat().

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The mkdir() function creates a new subdirectory named path.
The path can be relative to the current working directory or it can be
an absolute path name.

The directory's owner ID is set to the process's effective user ID.


The directory's group ID is set to the group ID of the parent directory (if
the parent set-group ID bit is set) or to the process's effective group ID.
The newly created directory is empty.
The mkdir() function marks the st_atime, st_ctime, and st_mtime
fields of the directory for update. Also, the st_ctime and st_mtime fields
of the parent directory are also updated.

Returns:
0, or -1 if an error occurs (errno is set).

Errors:
EACCES
Search permission is denied for a component of path, or write
permission is denied on the parent directory of path.
EEXIST
The directory named by path already exists.
ELOOP
Too many levels of symbolic links.
EMLINK
The link count of the parent directory would exceed LINK_MAX.
ENAMETOOLONG
The length of path exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.

13
ENOENT
A pathname component in the specified path does not exist, or
path is an empty string.

ENOSPC
The filesystem does not contain enough space to hold the
contents of the new directory or to extend the parent directory.
ENOSYS
This function is not supported for this path.
ENOTDIR
A component of path is not a directory.
EROFS
The parent directory resides on a read-only filesystem.

Examples:
To make a new directory called /src in /hd:
#include <sys/types.h>

#include <sys/stat.h>

#include <stdlib.h>

int main( void )


{
(void)mkdir( "/hd/src", S_IRWXU | S_IRGRP | S_IXGRP |S_IROTH |
S_IXOTH );
return EXIT_SUCCESS;
}
rmdir():
Delete an empty directory

Synopsis:
#include <sys/types.h>

#include <unistd.h>

int rmdir( const char* path );

Arguments:
path

14
The path of the directory that you want to delete. This path can
be relative to the current working directory, or an absolute path.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The rmdir() function removes (deletes) the specified directory. The
directory must not contain any files or directories.

If the directory is the current working directory of any process,


rmdir() returns -1 and sets errno to EINVAL. If the directory is the
root directory, the effect of this function depends on the filesystem.

The space occupied by the directory is freed, making it


inaccessible, if its link count becomes zero and no process has the
directory open (opendir()).

If a process has the directory open when the last link is removed,
the . and .. entries are removed and no new entries can be created in
the directory. In this case, the directory will be removed when all
references to it have been closed (closedir()).

When successful, rmdir() marks st_ctime and st_mtime for


update in the parent directory.

Returns:
0
Success.
-1
An error occurred (errno is set).

Errors:
EACCES
Search permission is denied for a component of path, or write
permission is denied on the parent directory of the directory to
be removed.
EBUSY
The directory named by path can't be removed because it's
being used by another process, and the implementation
considers this to be an error.

15
EEXIST
The path argument names a directory that isn't empty.
ELOOP
Too many levels of symbolic links.
ENAMETOOLONG
The argument path exceeds PATH_MAX in length, or a pathname
component is longer than NAME_MAX.
ENOENT
The specified path doesn't exist, or path is an empty string.
ENOSYS
The rmdir() function isn't implemented for the filesystem
specified in path.
ENOTDIR
A component of path isn't a directory.
ENOTEMPTY
The path argument names a directory that isn't empty.
EROFS
The directory entry to be removed resides on a read-only
filesystem.

Examples:
To remove the directory called /home/terry:
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
int main( void )
{
(void)rmdir( "/home/terry" );

return EXIT_SUCCESS;
}

16
chdir():
Change the current working directory

Synopsis:
#include <unistd.h>

int chdir( const char* path );

Arguments:
path
The new current working directory.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The chdir() function changes the current working directory to
path, which can be relative to the current working directory or an
absolute path name.

Returns:
0
Success.
-1
An error occurred (errno is set).

Errors:
EACCES
Search permission is denied for a component of path.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The path argument is longer than PATH_MAX, or a pathname
component is longer than NAME_MAX.
ENOENT
The specified path doesn't exist, or path is an empty string.
ENOMEM
There wasn't enough memory to allocate a control structure.
ENOSYS
The chdir() function isn't implemented for the filesystem
specified in path.

17
ENOTDIR
A component of path is not a directory.
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main( int argc, char* argv[] )


{
if( argc != 2 ) {
fprintf( stderr, "Use: cd <directory>\n" );
return EXIT_FAILURE;
}

if( chdir( argv[1] ) == 0 ) {


printf( "Directory changed to %s\n", argv[1] );
return EXIT_SUCCESS;
} else {
perror( argv[1] );
return EXIT_FAILURE;
}
}

getcwd():
Get the name of the current working directory

Synopsis:
#include <unistd.h>

char* getcwd( char* buffer, size_t size );

Arguments:
buffer
NULL, or a pointer to a buffer where the function can store the
directory name.
size
The size of the buffer, in bytes.

18
Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The getcwd() function returns the name of the current working
directory. buffer is a pointer to a buffer of at least size bytes where the
NUL-terminated name of the current working directory will be placed.

The maximum size that might be required for buffer is


PATH_MAX + 1 bytes. See <limits.h>.

POSIX doesn't specify what should happen if you call getcwd( NULL,
0). The Neutrino version (like many others) allocates a buffer for the
name of the directory; it's up to your application to free the buffer
when you no longer need it.

Returns:
The address of the string containing the name of the current working
directory, or NULL if an error occurred (errno is set).

Errors:
EINVAL
The argument size is negative or 0.

ELOOP
Too many levels of symbolic links.
ENOSYS
The getcwd() function isn't implemented for the filesystem
specified in the current working directory.
ERANGE
The buffer is too small (as specified by size) to contain the name
of the current working directory.

Examples:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>

int main( void )


{

19
char* cwd;
char buff[PATH_MAX + 1];

cwd = getcwd( buff, PATH_MAX + 1 );


if( cwd != NULL )
{
printf( "My working directory is %s.\n", cwd );
}

return EXIT_SUCCESS;
}
produces the output:
My working directory is /home/bill.

Scanning Directories:
opendir():
Open a directory

Synopsis:
20
#include <dirent.h>
DIR * opendir( const char * dirname );

Arguments:
dirname
The path of the directory to be opened. It can be relative to the
current working directory, or an absolute path.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The opendir() function is used with readdir() and closedir() to get
the list of file names contained in the directory specified by dirname.
You can read more than one directory at the same time using the
opendir(), readdir(), rewinddir() and closedir() functions.

The result of using a directory stream after one of the exec*() or


spawn*() functions is undefined. After a call to the fork() function,
either the parent or the child (but not both) can continue processing
the directory stream using readdir() and rewinddir(). If both the
parent and child processes use these functions, the result is
undefined. Either process can use closedir().

Returns:
A pointer to a DIR structure required for subsequent calls to readdir()
to retrieve the file names in dirname, or NULL if dirname isn't a valid
path (errno is set).

Errors:
EACCES
Search permission is denied for a component of dirname, or read
permission is denied for dirname.
ELOOP
Too many levels of symbolic links or prefixes.

ENAMETOOLONG
The length of dirname exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.
ENOENT
The named directory doesn't exist.
ENOSYS

21
The opendir() function isn't implemented for the filesystem
specified in dirname.
ENOTDIR
A component of dirname isn't a directory.

Examples:
Get a list of files contained in the directory /home/fred:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main( void )


{
DIR* dirp;
struct dirent* direntp;

dirp = opendir( "/home/fred" );


if( dirp == NULL ) {
perror( "can't open /home/fred" );
} else {
for(;;) {
direntp = readdir( dirp );
if( direntp == NULL ) break;

printf( "%s\n", direntp->d_name );


}
closedir( dirp );
}
return EXIT_SUCCESS;
}
readdir():
Read a directory entry

Synopsis:
#include <dirent.h>

22
struct dirent * readdir( DIR * dirp );

Arguments:
dirp
A pointer to the directory stream to be read.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.

Description:
The readdir() function reads the next directory entry from the
directory specified by dirp, which is the value returned by a call to
opendir().

You can call readdir() repeatedly to list all of the entries


contained in the directory specified by the pathname given to
opendir(). The closedir() function must be called to close the directory
stream and free the memory allocated by opendir().

The <dirent.h> file defines the struct dirent and the DIR type
used by the readdir() family of functions.

The result of using a directory stream after one of the exec*() or


spawn*() family of functions is undefined. After a call to fork(),
either the parent or the child (but not both) can continue processing
the directory stream, using the readdir() and rewinddir() functions.
If both the parent and child processes use these functions, the
result is undefined. Either (or both) processes may use closedir().

The <dirent.h> file also defines the following macros for accessing
extra data associated with the dirent structure:
_DEXTRA_FIRST( pdirent )
Get a pointer to the first block of data associated with the
structure pointed to by pdirent.
_DEXTRA_NEXT( last)
Get the block of data that follows the block pointed to by last.
_DEXTRA_VALID( extra, pdirent)
Evaluates to 1 if extra is a pointer to a valid block of data
associated with the structure pointed to by pdirent.
You can use these macros to traverse the data associated with the
dirent structure like this:

23
for( extra = _DEXTRA_FIRST(dirent);

_DEXTRA_VALID(extra, dirent);

extra = _DEXTRA_NEXT(extra)) {

switch(extra->d_type) {

/* No data */

case _DTYPE_NONE :

break;

/* Data includes information as returned by stat() */

case _DTYPE_STAT :

break;

/* Data includes information as returned by lstat() */

case _DTYPE_LSTAT :

break;

Returns:
A pointer to a struct dirent object for success, or NULL if the end of the
directory stream is encountered or an error occurs (errno is set).

• A returned value of NULL is ambiguous; if you need to


determine if it indicates an error (as opposed to the end of the
directory stream), set errno to EOK before each call to this
function.
• Although dirent is declared with a one-byte d_name field,
the structure that readdir() returns is allocated with enough

24
space to hold the entire name.

• Subsequent calls to readdir() with the same directory


stream may overwrite the memory that the returned pointer
points to.

Errors:
EBADF
The dirp argument doesn't refer to an open directory stream.
EOVERFLOW
One of the values in the structure to be returned can't be
represented correctly.

Examples:
Get a list of files contained in the directory /home/fred:
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main( void )
{
DIR* dirp;
struct dirent* direntp;

dirp = opendir( "/home/fred" );


if( dirp != NULL ) {
for(;;) {
direntp = readdir( dirp );
if( direntp == NULL ) break;

printf( "%s\n", direntp->d_name );


}

closedir( dirp );

return EXIT_SUCCESS;
}

return EXIT_FAILURE;
}

closedir():
Close a directory

25
Synopsis:
#include <dirent.h>

int closedir( DIR * dirp );

Arguments:
dirp
A directory pointer for the directory you want to close.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.
Description:
The closedir() function closes the directory specified by dirp, and frees
the memory allocated by opendir().

The result of using a directory stream after calling one of the


exec*() or spawn*() family of functions is undefined. After a call to
the fork() function, either the parent or the child (but not both) may
continue processing the directory stream using the readdir() and
rewinddir() functions. If both the parent and child processes use
these functions, the result is undefined. Either or both processes
may call the closedir() function.

Returns:
0
Success.
-1
An error occurred (errno is set).

Errors:
EBADF
The dirp argument doesn't refer to an open directory stream.
EINTR
The closedir() call was interrupted by a signal.

Examples:
Get a list of files contained in the directory /home/kenny:

#include <stdio.h>
#include <dirent.h>

26
#include <stdlib.h>

int main( void )


{
DIR *dirp;
struct dirent *direntp;

dirp = opendir( "/home/kenny" );


if( dirp != NULL )
{
for(;;) {
direntp = readdir( dirp );
if( direntp == NULL )
{
break;
}

printf( "%s\n", direntp->d_name );


}

closedir( dirp );

return EXIT_SUCCESS;
}

return EXIT_FAILURE;
}

rewinddir():
Rewind a directory stream to the start of the directory

Synopsis:

27
#include <sys/types.h>

#include <dirent.h>

void rewinddir( DIR * dirp );

Arguments:
dirp
A pointer to the directory stream of the directory to rewind.

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.
Description:
The rewinddir() function rewinds the directory stream specified
by dirp to the start of the directory. The directory stream will now refer
to the current state of the directory, as if the calling thread had called
opendir() again.

The result of using a directory stream after one of the exec*() or


spawn*() family of functions is undefined. After a call to fork(),
either the parent or the child (but not both) can continue processing
the directory stream, using the readdir() and rewinddir() functions.
If both the parent and child processes use these functions, the
result is undefined. Either (or both) processes may use closedir().

Examples:
List all the files in a directory, create a new file, and then list the
directory contents again:
#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <dirent.h>

#include <stdlib.h>

int main( void )

28
{
DIR *dirp;
struct dirent *direntp;
int filedes;
dirp = opendir( "/home/fred" );
if( dirp != NULL )
{
printf( "Old directory listing\n" );
for(;;) {
direntp = readdir( dirp );
if( direntp == NULL ) break;
printf( "%s\n", direntp->d_name );
}
filedes = creat( "/home/fred/file.new",
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
close( filedes );

rewinddir( dirp );
printf( "New directory listing\n" );
for(;;) {
direntp = readdir( dirp );
if( direntp == NULL ) break;
printf( "%s\n", direntp->d_name );
}
closedir( dirp );
}
return EXIT_SUCCESS;
}

seekdir():
Set the position for the next read of the directory stream

Synopsis:
#include <dirent.h>

29
void seekdir( DIR * dirp, long int pos );

Arguments:
dirp
A pointer to the directory stream, for which you want to set the
current location.
pos
The new position for the directory stream. You should have
obtained this value from an earlier call to telldir().

Library:
libc
Use the -l c option to qcc to link against this library. This library is
usually included automatically.
Description:
The seekdir() function sets the position of the next readdir()
operation on the directory stream specified by dirp to the position
specified by pos.

The new position reverts to the one associated with the directory
stream when the telldir() operation was performed.

Values returned by telldir() are good only for the lifetime of the
DIR pointer, dirp, from which they're derived. If the directory is closed
and then reopened, the telldir() value may be invalidated due to
undetected directory compaction. It's safe to use a previous telldir()
value immediately after a call to opendir() and before any calls to
readdir().

telldir():
Get the location associated with the directory stream

Synopsis:
#include <dirent.h>

long int telldir( DIR * dirp );

Arguments:

30
dirp
The directory stream for which you want to get the current
location.

Library:
libc
Use the -l c option to qcc to link against this library. This library
is usually included automatically.

Description:
The telldir() function obtains the current location associated with
the directory stream specified by dirp.

Returns:
Upon successful completion, telldir() shall return the current
location of the specified directory stream.
(or)
The current position of the specified directory stream, or -1 if an
error occurs (errno is set).

Errors:
EBADF
The dirp argument doesn't refer to an open directory stream.

31

You might also like