Reputation: 47
Just wondering, given the following code code snippet
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
void do_ls(char []);
main(int ac, char *av[])
{
if ( ac == 1 )
do_ls( "." );
else
while ( --ac ){
printf("%s:\n", *++av );
do_ls( *av );
}
}
void do_ls( char dirname[] )
{
DIR *dir_ptr; /* the directory */
struct dirent *direntp; /* each entry */
if ( ( dir_ptr = opendir( dirname ) ) == NULL )
fprintf(stderr,"ls1: cannot open %s\n", dirname);
else
{
while ( ( direntp = readdir( dir_ptr ) ) != NULL )
printf("%s\n", direntp->d_name[0] );
closedir(dir_ptr);
}
}
Instead of getting the whole name of each entry, how do I get a specific character of each entry (for example the first character in the name) instead of the whole name. In the code I tried to use direntp->d_name[0]
but it didn't work.
Any help/tips would be greatly appreciated.
Upvotes: 1
Views: 1652
Reputation: 70911
Change this:
printf("%s\n", direntp->d_name[0] );
to be
printf("%c\n", direntp->d_name[0]);
From the C11 Standard (draft):
7.21.6.1 The
fprintf
function[...]
8 The conversion specifiers and their meanings are:
c
[...] the int argument is converted to an unsigned char, and the resulting character is written. [...]
s
[...] the argument shall be a pointer to the initial element of an array of character type.280) Characters from the array are written up to (but not including) the terminating null character. [...]
Upvotes: 0
Reputation: 16122
Change the %s
to %c
in your printf
, this will print a character.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
void do_ls(char []);
int main(int ac, char *av[])
{
if ( ac == 1 )
do_ls( "." );
else {
while ( --ac ) {
printf("%s:\n", *++av );
do_ls( *av );
}
}
return 0;
}
void do_ls( char dirname[] )
{
DIR *dir_ptr; /* the directory */
struct dirent *direntp; /* each entry */
if ( ( dir_ptr = opendir( dirname ) ) == NULL )
fprintf(stderr,"ls1: cannot open %s\n", dirname);
else
{
while ( ( direntp = readdir( dir_ptr ) ) != NULL )
printf("%c\n", direntp->d_name[0] );
closedir(dir_ptr);
}
}
Upvotes: 1