stat() returns error - c

I have to know the modification date of some files in a folder. It works, but not with all types of files.
For example it works with .c, .txt, but it doesn't work with other types such .mp4, .jpg and .mp3 (the application I'm creating have to work with multimedia files in general). It prints "Cannot display the time.", so I suppose the problem is on stat(). Thanks.
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
char parola[12]="", hash[32]="", esadecimale[1000]="", system3[100]="./md5 ";
int i, len, len2;
int bytes;
char cwd[1024];
int main(void)
{
char t[100] = "";
struct stat b;
DIR *dp;
char destinationFolder[100] = "/Users/mattiazeni/Desktop/Prova/"; //Me la passa da sopra
struct dirent *dir_p;
dp = opendir(destinationFolder);
if ( dp == NULL ) exit(1);
len = strlen(destinationFolder);
for (i=0;i<len;i++) {
system3[i+6]=destinationFolder[i];
}
while( ( dir_p = readdir(dp) ) != NULL ) {
if (dir_p -> d_name[0] != '.') {
//printf("%s\n", dir_p -> d_name);
len2 = strlen(dir_p -> d_name);
for (i=0;i<len2;i++) {
if (dir_p -> d_name[i] == ' '){ //Mi serve per correggere i nomi dei file con spazi
system3[i+len+6]='\\';
}
else system3[i+len+6]=dir_p -> d_name[i];
}
system(system3); //Passa il valore a md5 che calcola l'hash e lo stampa nel file che ci serve insieme al persorso/nome del file
FILE *fp;
if((fp=fopen("userDatabase.txt", "ab"))==NULL) {
printf("Error while opening the file..\n");
fclose (fp);
}
else {
if (!stat(dir_p -> d_name, &b)) {
strftime(t, 100, "%d/%m/%Y %H:%M:%S", localtime( &b.st_mtime)); //C'è ancora qualche errore!!
fprintf(fp, "%s", t);
}
else {
perror(0);
fprintf(fp, "error");
}
fprintf(fp, " initialized");
fprintf(fp, "\n");
}
fclose (fp);
for (i=len+6;i<len+6+len2;i++) {
system3[i]=' ';
}
}
}
closedir(dp);
return 0;
}

Use perror(). Also shouldn't you use st_mtime?
stat:
On success, zero is returned.
On error, -1 is returned, and errno is set appropriately.
99% sure it is because dir_p -> d_name does not exist, which in turn probably is because of a localization issue.
You could do something like:
fprintf(stderr,
"Unable to stat %s\n",
dir_p->d_name);
perror(0);
Also; shouldn't it be ->f_name and not ->d_name if you are checking file status? - (Unless you use d_name for file name off course.)
And your fclose(fp) is outside your fp == NULL check. As you do not return or otherwise abort the flow you risk an SIGSEGV if the fopen fail.
Edit: What do you get with something like this?
#include <unistd.h>
char cwd[1024];
...
} else {
fprintf(stderr,
"Unable to stat '%s'\n",
dir_p->d_name);
perror(0);
if (getcwd(cwd, sizeof(cwd)) == NULL) {
perror("getcwd() error");
} else {
fprintf(stderr,
"in directory '%s'\n",
cwd);
}
}
Edit2:
First; I said getcwd() != NULL should be ==. Se change. (Bad by me.)
The problem in your code. (There is a few more) but regarding stat - you use d_name from readdir. This is only filename; not dir+filename. Thus; you get i.e.:
stat(dir_p->d_name, ...)
Which becomes i.e.:
stat("file.mp4", ...)
Easiest quick-fix (tho dirty) would be:
/* you need to terminate the system string after your for loop */
system3[i + len + 6] = '\0';
system(system3);
if (!stat(system3 + 6, &b)) {

You should use the complete pathname for stat(). Stat does not know which directory you are interested in.
...
char bigbuff[PATH_MAX];
sprintf( bigbuff, "%s/%s", destinationFolder, dir_p->d_name);
rc = stat (bigbuff, &b);
...

This is the final working code in order to scan a directory for files, and print them on a txt output file with the modification date:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
char system3[6]="./md5 ";
int main(void)
{
char t[100] = "";
char bigbuff[200];
struct stat b;
char destinationFolder[100] = "/Users/mattiazeni/Desktop/Prova"; //Me la passa da sopra
DIR *dp;
struct dirent *dir_p;
dp = opendir(destinationFolder);
if ( dp == NULL ) exit(1);
while( ( dir_p = readdir(dp) ) != NULL ) {
if (dir_p -> d_name[0] != '.') {
sprintf( bigbuff, "%s%s/%s",system3, destinationFolder, dir_p->d_name);
system(bigbuff);
FILE *fp;
if((fp=fopen("userDatabase.txt", "ab"))==NULL) {
printf("Error while opening the file..\n");
fclose (fp);
}
else {
sprintf( bigbuff, "%s/%s", destinationFolder, dir_p->d_name);
if (!stat(bigbuff, &b)) {
strftime(t, 100, "%d/%m/%Y %H:%M:%S", localtime( &b.st_mtime)); //C'è ancora qualche errore!!
fprintf(fp, "%s", t);
}
else {
perror(0);
fprintf(fp, "error");
}
fprintf(fp, "\n");
}
fclose (fp);
}
}
closedir(dp);
return 0;
}
Thanks all for the help!

Related

This code emulates command ls|cat -n, but i need to transmit the needed directory through stdin instead of ".", how can i do it?

#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent *de;
DIR *dr;
int i = 1;
dr = opendir("."); // need to get directory through stdin insted of this
if (dr == NULL) printf("Could not open directory");
while (((de = readdir(dr)) != NULL))
{
printf("\t%d. %s\n", i, de -> d_name);
i++;
}
closedir(dr);
return 0;
}
You read it from stdin and use in place of ".". Here is the full example
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
int main(){
struct dirent *de;
char dirbuf[BUFSIZ] = {0};
DIR *dr;
int i = 1;
puts("Chose the directory: ");
if (fgets(dirbuf, BUFSIZ, stdin) == NULL) {
perror("fgets");
exit(-1);
}
dirbuf[strlen(dirbuf)-1] = '\0'; // remove \n
dr = opendir(dirbuf); // need to get directory through stdin insted of this
if (dr == NULL) {
perror("opendir");
exit(-1);
}
while(((de = readdir(dr)) != NULL))
{
printf("\t%d. %s\n", i, de -> d_name);
i++;
}
closedir(dr);
return 0;
}

Linux cp command implementation to copy multiple files to a Directory

I'm currently learning systems programming and came across an implementation of the Linux cp command in C. This implementation though from my understanding allows for copying the contents of one file to another file in the same directory and also copying a file into a Directory in the current directory.
How could you change this code to allow for multiple files to be copied to a directory at once (i.e "copy f1.txt f2.txt f3.txt /dirInCurrentDir")
or even ("copy d1/d2/d3/f1 d4/d5/d6/f2 d ") which would copy the 2 files to directory d. I know that the changes would have to occur in main() but how could you add to the if-else statement?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFFERSIZE 1024
#define COPYMORE 0644
void oops(char *, char *);
int copyFiles(char *src, char *dest);
int dostat(char *filename);
int mode_isReg(struct stat info);
int main(int ac, char *av[])
{
/* checks args */
if(ac != 3)
{
fprintf(stderr, "usage: %s source destination\n", *av);
exit(1);
}
char *src = av[1];
char *dest = av[2];
if( src[0] != '/' && dest[0] != '/' )//cp1 file1.txt file2.txt
{
copyFiles(src, dest);
}
else if( src[0] != '/' && dest[0] == '/' )//cp1 file1.txt /dir
{
int i;
for(i=1; i<=strlen(dest); i++)
{
dest[(i-1)] = dest[i];
}
strcat(dest, "/");
strcat(dest, src);
copyFiles(src, dest);
}
else
{
fprintf(stderr, "usage: cp1 source destination\n");
exit(1);
}
}
int dostat(char *filename)
{
struct stat fileInfo;
//printf("Next File %s\n", filename);
if(stat(filename, &fileInfo) >=0)
if(S_ISREG(fileInfo.st_mode))
return 1;
else return 0;
return;
}
int copyFiles(char *source, char *destination)
{
int in_fd, out_fd, n_chars;
char buf[BUFFERSIZE];
/* open files */
if( (in_fd=open(source, O_RDONLY)) == -1 )
{
oops("Cannot open ", source);
}
if( (out_fd=creat(destination, COPYMORE)) == -1 )
{
oops("Cannot create ", destination);
}
/* copy files */
while( (n_chars = read(in_fd, buf, BUFFERSIZE)) > 0 )
{
if( write(out_fd, buf, n_chars) != n_chars )
{
oops("Write error to ", destination);
}
if( n_chars == -1 )
{
oops("Read error from ", source);
}
}
/* close files */
if( close(in_fd) == -1 || close(out_fd) == -1 )
{
oops("Error closing files", "");
}
return 1;
}
void oops(char *s1, char *s2)
{
fprintf(stderr, "Error: %s ", s1);
perror(s2);
exit(1);
}
You would loop through all the argument values (from av[1] to av[ac - 2]) and copy it to the destination argument, which would be av[ac - 1].
In your case, you would pass av[i] and av[ac - 1] to the copyFiles function, where i would be your loop index.

fopen: file does not exist but it does

I want to read all files that I can find in the folder where my executable is, except the runnable file that I'm running. I code the following code but, although this list correctly the files that I have in my folder, I cannot open them with fopen because fopen prints that the file doesn't exists. If I do gedit "path of the file obtained from my program in c" then it opens perfectly from the term. Where is the bug?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
int main (int argc, char **argv) {
//Determining the number of files we have.
//We call to a bash command http://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output
FILE *fp, *fin;
char path[1035], cwd[1024];
int scanned = 0;
/* Open the command for reading. */
//https://askubuntu.com/questions/370697/how-to-count-number-of-files-in-a-directory-but-not-recursively
//This count soft and hard links also (I think)
fp = popen("ls -F |grep -v /", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
//Loop for each file. Be careful! if the exe is inside, it will also be counted!
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("Reading file: %s\n", path);
fin=fopen(path,"r");
scanned = 0;
printf("caa");
if (fin != NULL){
printf("AA\n");
fclose(fin);
}
if (!fin)perror("fopen");
printf("Done! \n");
}
/* close */
pclose(fp);
printf("end");
return 0;
}
There are 2 bugs in your code:
when the code updates the "path" variable in your code. It has a newline at the end which needs to be corrected to NUL. This gives an incorrect path.
Something like below can be appended to your code:
while (fgets(path, sizeof(path)-1, fp) != NULL) {
len=strlen(path);
path[len-1]='\0';
Use 'ls -A1', since 'ls -F' adds a '*' in binary name:
fp = popen("ls -A1 |grep -v /", "r");
ok so just in case someone else needs a better approach, I redid the code with the comments I had. Here I let you the new code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
int main (int argc, char **argv) {
FILE *fp, *fin;
char path[1035], cwd[1024];
int scanned = 0;
int ints;
DIR *dir;
struct dirent *ent;
//getcwd prints directory where the app ran.
if ((dir = opendir (getcwd(cwd, sizeof(cwd)))) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
/*Skips . and ..*/
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
if (isDirectory(ent->d_name) != 0) continue;
printf ("Reading file: %s\n", ent->d_name);
scanned = 0;
fin=fopen(ent->d_name,"r");
if (fin != NULL){
while ((scanned = fscanf(fin, "%d", ints)) != EOF) {
if(scanned == 1){
printf("%d\n", ints);
}else {
printf("Whoops! Input format is incorrect!\n");
break;
}
} //LOOP: reading file
fclose(fin);
}
if (!fin)perror("fopen");
printf("Done! \n");
}//LOOP: while opendir
closedir (dir);
} else {
/* could not open directory */
perror ("opendir");
return EXIT_FAILURE;
}
return 0;
}

Opening a file using relative path

The following code is supposed to work as follows: print the list of the files in a directory, and print the content of each .c file.
it works fine when executed in UNIX for the same directory: ./a.out ./
However, I was not able to make it work for ./a.out ../differentDir execution.
I know that if the absolute path is provided as an argument, I could use argv[1] for that. However, when it is provided in a form of a relative path I am lost.
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFSIZE 32768
int main(int argc, char **argv) {
char buf[BUFFSIZE];
DIR *dp;
struct dirent *dirp;
char filename[80];
int name_length;
FILE *fp;
if (argc != 2) {
fprintf(stderr, "usage: %s dir_name\n", argv[0]);
exit(1);
}
if ((dp = opendir(argv[1])) == NULL ) {
fprintf(stderr, "can't open '%s'\n", argv[1]);
exit(1);
}
while ((dirp = readdir(dp)) != NULL ){
printf("%s\n", dirp->d_name);
memset(filename, '\0', sizeof(filename));
strcpy(filename, dirp->d_name);
printf(" ** %s ", filename);
name_length = strlen(filename);
printf(" name_length=%d \n", name_length);
if (findC(filename)) // checking if the file has a .c extension
{
fp=fopen(filename, "r");
if (fp == NULL)
fprintf(stderr, "Can't open .C file!\n");
else
{// if the file was opened successfuly:
do
{
fgets(buf,BUFFSIZE,fp); // reading each line until buffer is full or until reaching whitespace
buf[strlen(buf)-1]='\0'; // removing the trailing whitespace from the buffer
puts(buf);
}
while (!feof(fp));
printf("\n\n");
fclose(fp);
}
}
}
closedir(dp);
return(0);
}
/*FindC method gets a c-string that represents a file name; returns 1 if the file ends with .C extension, else returns 0*/
int findC(char * name)
{
int len = strlen(name);
if (len>=2 && name[len-2]=='.' && tolower(name[len-1])=='c')
return 1;
return 0;
}
Upon opening the file to read, the file pathname needs to also be relative.
// Form prefix for complete relative file name
char filename[MAXPATH];
strcpy(filename, argv[1]);
// append '/' if directory path does not end in '/'
if (TBD_code(filename)) {
strcat(filename, "/");
}
char *end = filename[strlen(filename)];
while ((dirp = readdir(dp)) != NULL ){
printf("%s\n", dirp->d_name);
if (findC(dirp->d_name)) {
// append filename to prefix
strcpy(end, dirp->d_name);
fp=fopen(filename, "r");
...
You can use realpath(argv1...) like in this example. realpath will return the absolute path for a relative path.
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
int main(int argc, char **argv) {
char *path = "../..";
char buff[PATH_MAX + 1]; /* not sure about the "+ 1" */
char *res = realpath(path, buff);
if (res) {
printf("This source is at %s.\n", buff);
} else {
perror("realpath");
exit(EXIT_FAILURE);
}
return 0;
}
To include the desired behavior in your program, you can use realpathin your code:
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <dirent.h>
#include <string.h>
#define BUFFSIZE 32768
int main(int argc, char **argv) {
char buf[BUFFSIZE];
DIR *dp;
struct dirent *dirp;
char filename[80];
int name_length;
FILE *fp;
char buff[PATH_MAX + 1]; /* not sure about the "+ 1" */
if (argc != 2) {
fprintf(stderr, "usage: %s dir_name\n", argv[0]);
exit(1);
}
char *res = realpath(argv[1], buff);
if ((dp = opendir(res)) == NULL ) {
fprintf(stderr, "can't open '%s'\n", argv[1]);
exit(1);
}
while ((dirp = readdir(dp)) != NULL ){
printf("%s\n", dirp->d_name);
memset(filename, '\0', sizeof(filename));
strcpy(filename, dirp->d_name);
printf(" ** %s ", filename);
name_length = strlen(filename);
printf(" name_length=%d \n", name_length);
if (findC(filename)) // checking if the file has a .c extension
{
fp=fopen(filename, "r");
if (fp == NULL)
fprintf(stderr, "Can't open .C file!\n");
else
{// if the file was opened successfuly:
do
{
fgets(buf,BUFFSIZE,fp); // reading each line until buffer is full or until reaching whitespace
buf[strlen(buf)-1]='\0'; // removing the trailing whitespace from the buffer
puts(buf);
}
while (!feof(fp));
printf("\n\n");
fclose(fp);
}
}
}
closedir(dp);
return(0);
}
/*FindC method gets a c-string that represents a file name; returns 1 if the file ends with .C extension, else returns 0*/
int findC(char * name)
{
int len = strlen(name);
if (len>=2 && name[len-2]=='.' && tolower(name[len-1])=='c')
return 1;
return 0;
}
You could first change to the directory chdir either with relative or absolute path and the get the absolute path via the getcwd
#include <sys/types.h>
#include <string.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFSIZE 32768
#define PATH_SIZE 512
int main(int argc, char **argv) {
char buf[BUFFSIZE];
char path[PATH_SIZE];
DIR *dp;
struct dirent *dirp;
char filename[80];
int name_length, r;
FILE *fp;
if (argc != 2) {
fprintf(stderr, "usage: %s dir_name\n", argv[0]);
exit(1);
}
strcpy(path, argv[1]);
r = chdir(path);
if( r != 0 )
{
printf("Invalid path '%s'\n",path);
exit(1);
}
getcwd(path,PATH_SIZE);
if ((dp = opendir(path)) == NULL ) {
fprintf(stderr, "can't open '%s'\n", argv[1]);
exit(1);
}
while ((dirp = readdir(dp)) != NULL ){
printf("%s\n", dirp->d_name);
memset(filename, '\0', sizeof(filename));
strcpy(filename, dirp->d_name);
printf(" ** %s ", filename);
name_length = strlen(filename);
printf(" name_length=%d \n", name_length);
if (findC(filename)) // checking if the file has a .c extension
{
fp=fopen(filename, "r");
if (fp == NULL)
fprintf(stderr, "Can't open .C file!\n");
else
{// if the file was opened successfuly:
do
{
fgets(buf,BUFFSIZE,fp); // reading each line until buffer is full or until reaching whitespace
buf[strlen(buf)-1]='\0'; // removing the trailing whitespace from the buffer
puts(buf);
}
while (!feof(fp));
printf("\n\n");
fclose(fp);
}
}
}
closedir(dp);
return(0);
}
/*FindC method gets a c-string that represents a file name; returns 1 if the file ends with .C extension, else returns 0*/
int findC(char * name)
{
int len = strlen(name);
if (len>=2 && name[len-2]=='.' && tolower(name[len-1])=='c')
return 1;
return 0;
}

Listing directories in Linux from C

I am trying to simulate linux command ls using linux api from c. Looking at the code it does make sense, but when I run it I get "stat error: No such file or directory". I have checked that opendir is working ok. I think the problem is in stat, which is returning -1 even though I think it should return 0.
What am I missing?
Thanks for your help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
int main(int argc, char *argv[])
{
DIR *dirp;
struct dirent *direntp;
struct stat stat_buf;
char *str;
if (argc != 2)
{
fprintf( stderr, "Usage: %s dir_name\n", argv[0]);
exit(1);
}
if ((dirp = opendir( argv[1])) == NULL)
{
perror(argv[1]);
exit(2);
}
while ((direntp = readdir( dirp)) != NULL)
{
if (stat(direntp->d_name, &stat_buf)==-1)
{
perror("stat ERROR");
exit(3);
}
if (S_ISREG(stat_buf.st_mode)) str = "regular";
else if (S_ISDIR(stat_buf.st_mode)) str = "directory";
else str = "other";
printf("%-25s - %s\n", direntp->d_name, str);
}
closedir(dirp);
exit(0);
}
It's because you aren't stating the actual file. It's in a different directory. If you want the real filename, combine argv[1] and direntp->d_name with a '/' between them.
Also, hungarian naming is icky, even the minor bit like 'p' on the end. If you have so many variables you need to keep track of their types in their names you're doing something wrong.
Here is a revised version of your program:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include <sys/param.h>
int main(int argc, char *argv[])
{
DIR *dirp;
struct dirent *direntp;
struct stat stat_buf;
char *str;
char fullpath[MAXPATHLEN + 1];
size_t dirnamelen;
if (argc != 2)
{
fprintf( stderr, "Usage: %s dir_name\n", argv[0]);
exit(1);
}
strncpy(fullpath, argv[1], MAXPATHLEN - 1); /* account for trailing '/' */
fullpath[MAXPATHLEN - 1] = '\0';
dirnamelen = strlen(fullpath);
if (strlen(argv[1]) > dirnamelen) {
fprintf( stderr, "Directory name is too long: %s", argv[1] );
exit(2);
}
fullpath[dirnamelen++] = '/';
fullpath[dirnamelen] = '\0';
if ((dirp = opendir( argv[1])) == NULL)
{
perror(argv[1]);
exit(2);
}
while ((direntp = readdir( dirp)) != NULL)
{
fullpath[dirnamelen] = '\0';
if ((dirnamelen + strlen(direntp->d_name)) > MAXPATHLEN) {
fprintf(stderr, "File %s + directory %s is too long.", direntp->d_name, fullpath);
continue;
} else {
/* strncpy is mild overkill because the if statement has verified that
there's enough space. */
strncpy(fullpath + dirnamelen, direntp->d_name, MAXPATHLEN - dirnamelen);
fullpath[MAXPATHLEN] = '\0';
}
if (stat(fullpath, &stat_buf)==-1)
{
perror("stat ERROR");
exit(3);
}
if (S_ISREG(stat_buf.st_mode)) str = "regular";
else if (S_ISDIR(stat_buf.st_mode)) str = "directory";
else str = "other";
printf("%-25s - %s\n", direntp->d_name, str);
}
closedir(dirp);
exit(0);
}
Note that I use MAXPATHLEN (from <limits.h>) and carefully check to make sure there aren't any buffer overflows. You should do the same in your code.
Edit: Changed code to use strn family functions for added safety.
Add
#include <unistd.h>
...
chdir(argv[1]);
or call stat with the full pathname like this
...
char fullpath[MAXPATHLEN];
snprintf(fullpath, sizeof(fullpath), "%s/%s", argv[1], direntp->d_name);
if (stat(fullpath, &stat_buf) == -1)
...
Others have suggested building a full path for stat(), or using chdir(). Both those will work (although they are subject to a race condition, if the directory is renamed while you are in the middle of reading it).
An alternative, which is not subject to the race condition, and is therefore arguably more "correct", is to use fstatat(). Just replace your existing stat() call with:
fstatat(dirfd(dirp), direntp->d_name, &stat_buf, 0)
(The chdir() method can be made race-condition-free too: either by using fchdir(dirfd(dirp)) instead of chdir(), or by changing directory to argv[1] and then opening "." with opendir(). The pathname construction method can't be made race-condition-free).
Why dont you try this? Just give the path to argv[1] like this /home/sabri/Desktop/Test
int main(int argc, char *argv[])
{
struct dirent *direntp;
DIR *dirp;
if (argc != 2)
{
fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
return 1;
}
if ((dirp = opendir(argv[1])) == NULL)
{
perror ("Failed to open directory");
return 1;
}
while ((direntp = readdir(dirp)) != NULL)
printf("%s\n", direntp->d_name);
while ((closedir(dirp) == -1) && (errno == EINTR)) ;
return 0;
}
If you are using on unix, then you may use the system command.
system("ls -ltr | grep -d");

Resources