LinuxQuestions.org
Latest LQ Deal: Linux Power User Bundle
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices


Reply
  Search this Thread
Old 04-21-2013, 12:10 AM   #1
cou
LQ Newbie
 
Registered: Apr 2013
Posts: 2

Rep: Reputation: Disabled
Iam trying to write a c program for ls -l.....


Can someone help me to specify the directory name in particular instead of current working directory. My code is working well for current working directory but when I change to specific directory it seems not working

#include <string.h> /* String functions (strcat) */
#include <dirent.h> /* DIR, dirent, etc. */
#include <sys/stat.h> /* struct stat */
#include <sys/types.h> /* S_IFMT */
#include <stdio.h> /* sprintf, etc. */
#include <stdlib.h> /* exit, etc. */
#include <time.h> /* strftime, ctime */
#include <pwd.h> /* struc passwd (to retrieve user name) */
#include <grp.h> /* struc group (to retrieve group name) */
#define MAX_MSG_LEN 200 /* Maximum length of temporary string */

/* Define all the error messages */
char * error_msg[] = {
"\nUsage: ./13lsl\n\n",
"\nCould not retrieve the current working directory\n\n",
"\nCould not open the current working directory\n\n",
"\nError doing 'stat' on file\n\n",
"\nCould not scan the directory\n\n"
};

void print_error(int msg_num, int exit_code);

int main(int argc, char * argv[])
{
int i; /* A counter */
char msg[MAX_MSG_LEN] = ""; /* A temporary string */
struct passwd * passwd_details; /* Structure to retrieve user name */
struct group * group_details; /* Structure to retrieve group name */
struct tm * tmptime; /* To store file modification time in 'tm' struc */
char time_str[MAX_MSG_LEN]; /* String representation of time */
char mode_str[11]; /* String to hold file type and permissions */
mode_t file_perm; /* File permissions */
DIR * dir_to_read; /* Handle to directory to be read */
struct dirent ** dir_entry; /* Array to hold individual entries of dir sorted */
int num_entries; /* Number of entries in the directory */
struct stat file_details; /* Detailed file info */
char * cur_work_dir = NULL; /* String to hold current working directory name */
char success_msg[] = "\nCommand executed successfully\n\n";
/* Check if correct number of arguments are supplied */
if ( argc > 1 ) print_error(0,2);

/* Get the current working directory */
if ( (cur_work_dir = (char *)get_current_dir_name()) == NULL )
print_error(1,3);

/* Open the current working directory */
if ( (dir_to_read = opendir(cur_work_dir)) == NULL )
print_error(2,4);

/* Get the current directory alphabetically sorted */
if ( (num_entries = scandir(cur_work_dir, &dir_entry, 0, alphasort)) < 0 )
print_error(4,6);
else
{
/* Loop through sorted current working directory and display each file name till all the entries are exhausted */
for ( i = 0; i < num_entries; i++ )
{
/* Retrieve the file details */
if (lstat(dir_entry[i]->d_name,&file_details) < 0)
print_error(3,5);

/* Prepare the mode string */
/* Get the file type */
if ( S_ISREG(file_details.st_mode) ) strcpy(mode_str,"-");
else if ( S_ISDIR(file_details.st_mode) ) strcpy(mode_str,"d");
else if ( S_ISLNK(file_details.st_mode) ) strcpy(mode_str,"l");
else strcpy(mode_str,"?");

/* Get the octal file permissions */
file_perm = file_details.st_mode & ~S_IFMT;
if ( file_perm & S_IRUSR )
strcat(mode_str,"r");
else
strcat(mode_str,"-");
if ( file_perm & S_IWUSR )
strcat(mode_str,"w");
else
strcat(mode_str,"-");
if ( file_perm & S_IXUSR )
strcat(mode_str,"x");
else
strcat(mode_str,"-");
if ( file_perm & S_IRGRP )
strcat(mode_str,"r");
else
strcat(mode_str,"-");
if ( file_perm & S_IWGRP )
strcat(mode_str,"w");
else
strcat(mode_str,"-");
if ( file_perm & S_IXGRP )
strcat(mode_str,"x");
else
strcat(mode_str,"-");
if ( file_perm & S_IROTH )
strcat(mode_str,"r");
else
strcat(mode_str,"-");
if ( file_perm & S_IWOTH )
strcat(mode_str,"w");
else
strcat(mode_str,"-");
if ( file_perm & S_IXOTH )
strcat(mode_str,"x");
else
strcat(mode_str,"-");

/* Initialize the temporary string 'msg' */
strcpy(msg,"");

/* Get the file permissions in temporary string 'msg' */
sprintf(msg,"%s%s ",msg,mode_str);

/* Get the number of links */
sprintf(msg,"%s%d ",msg,(int)file_details.st_nlink);

/* Get the User name */
passwd_details = getpwuid(file_details.st_uid);
sprintf(msg,"%s%s ",msg,passwd_details->pw_name);

/* Get the Group name */
group_details = getgrgid(file_details.st_gid);
sprintf(msg,"%s%s ",msg,group_details->gr_name);

/* Get the size of the file */
sprintf(msg,"%s%6d ",msg,(int)file_details.st_size);

/* Get the last modification time of the file */
tmptime = localtime(&file_details.st_mtime);
strftime(time_str, sizeof(time_str), "%F %R", tmptime);
sprintf(msg,"%s%s ",msg,time_str);

/* Get the file name */
sprintf(msg,"%s%s\n",msg,dir_entry[i]->d_name);

/* Display file details */
printf("%s",msg);
} /* end for */
} /* end else */
printf("%s", success_msg);
return 1;
}

void print_error(int error_index, int exit_code)
{
fprintf(stderr, "%s", error_msg[error_index]);
exit(exit_code);
}
 
Old 04-21-2013, 12:23 AM   #2
shivaa
Senior Member
 
Registered: Jul 2012
Location: Grenoble, Fr.
Distribution: Sun Solaris, RHEL, Ubuntu, Debian 6.0
Posts: 1,800
Blog Entries: 4

Rep: Reputation: 286Reputation: 286Reputation: 286
Please use [code][code] around your commands/output/code for ease of readability.

Second, what error you are gettting and how are you invoking this code? Let's know 'where' are you stuck.

Last edited by shivaa; 04-21-2013 at 12:24 AM.
 
Old 04-21-2013, 12:47 AM   #3
jdkaye
LQ Guru
 
Registered: Dec 2008
Location: Westgate-on-Sea, Kent, UK
Distribution: Debian Testing Amd64
Posts: 5,465

Rep: Reputation: Disabled
Quote:
Originally Posted by shivaa View Post
Please use [code][code] around your commands/output/code for ease of readability.

...
Minor correction: it's /code surrounded by square brackets at the end.
jdk

Last edited by jdkaye; 04-21-2013 at 12:49 AM.
 
Old 04-21-2013, 01:05 AM   #4
jpollard
Senior Member
 
Registered: Dec 2012
Location: Washington DC area
Distribution: Fedora, CentOS, Slackware
Posts: 4,711

Rep: Reputation: 1279Reputation: 1279Reputation: 1279Reputation: 1279Reputation: 1279Reputation: 1279Reputation: 1279Reputation: 1279Reputation: 1279
So your problem is with:
Code:
...
/* Get the current working directory */
if ( (cur_work_dir = (char *)get_current_dir_name()) == NULL )
print_error(1,3);
...
Your problem is that get_current_dir_name is never null. BTW, it is already type "char *" so there is no need to cast it to a "char *"

What would be wrong with allowing multiple parameters? something like "app pathname".

Then:
Code:
    if (argc > 1) curr_work_dir = argv[1];
    if (curr_work_dir == NULL)
        cur_work_dir = get_current_dir_name();
 
Old 04-21-2013, 09:50 AM   #5
cou
LQ Newbie
 
Registered: Apr 2013
Posts: 2

Original Poster
Rep: Reputation: Disabled
The program is well running for the current working directory ....the output is fine....But i want to fix to a path just like
"/zzz/xxx/yyy"
can someone help me to fix the path instead of the current working directory
 
Old 04-21-2013, 11:17 AM   #6
johnsfine
LQ Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,286

Rep: Reputation: 1190Reputation: 1190Reputation: 1190Reputation: 1190Reputation: 1190Reputation: 1190Reputation: 1190Reputation: 1190Reputation: 1190
Quote:
Originally Posted by cou View Post
if ( argc > 1 ) print_error(0,2);
argc includes the command (argv[0]) so rejecting argc>1 is rejecting any arg after the command itself.

Quote:
Originally Posted by cou View Post
can someone help me to fix the path instead of the current working directory
That seems to be exactly what jpollard did already.

Did you try the code from that post?

Last edited by johnsfine; 04-21-2013 at 11:20 AM.
 
Old 02-27-2016, 12:13 AM   #7
justin0212
LQ Newbie
 
Registered: Feb 2016
Posts: 2

Rep: Reputation: Disabled
Slight amendment to the code

I have solved my issue and have remove my code. Sorry for any inconvenience.

Last edited by justin0212; 02-27-2016 at 12:43 AM. Reason: Solved for my issue
 
Old 02-27-2016, 12:03 PM   #8
rknichols
Senior Member
 
Registered: Aug 2009
Distribution: CentOS
Posts: 3,580

Rep: Reputation: 1566Reputation: 1566Reputation: 1566Reputation: 1566Reputation: 1566Reputation: 1566Reputation: 1566Reputation: 1566Reputation: 1566Reputation: 1566Reputation: 1566
Quote:
Originally Posted by jpollard View Post
Your problem is that get_current_dir_name is never null.
Actually get_current_dir_name() can return NULL. That happens if the process's CWD has been removed. Try running this in an empty directory:
Code:
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    char *cwd;
    int n;
    for(n = 0; n++ < 5; ) {
	if((cwd = get_current_dir_name()) != NULL) {
	    printf("CWD=%s\n", cwd);
	    if(rmdir(cwd) < 0) {
		perror("rmdir()");
	    }
	}
	else {
	    puts("CWD is NULL");
	    break;
	}
	sleep(2);
    }
    return 0;
}
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Best Program to write algorithm? twinsmurf Linux - Software 4 10-07-2010 03:54 PM
program that lets me write on the desktop itself? newbiesforever Linux - Software 2 12-17-2008 05:35 AM
C Program to write to the memory kushalkoolwal Programming 3 05-30-2008 06:11 PM
write a C++ program yewjingcho Programming 14 11-01-2007 07:05 PM
Write to port (C program) dummyagain Programming 8 10-24-2003 11:50 AM

LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 02:03 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration