how to implement "which " command in C? - c

I'm struggling to get the functionality of the "which command" that appears in LINUX, which I require to do the same in C.
I explain my question. In Linux Terminal, if I enter "which file1.txt", it searches in the entire filesystem and prints the path. The syntax for the same is "which ".
Similarly, I want to do the same functionality using the C program. I should only use C. Could anybody help me with how to complete this? I tried many ways, but unable to complete it.
#define _POSIX_SOURCE
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#undef _POSIX_SOURCE
#include <stdio.h>
void traverse(char *fn, int indent) {
DIR *dir;
struct dirent *entry;
int count;
char path[1025];
struct stat info;
for (count=0; count<indent; count++) printf(" ");
printf("%s\n", fn);
if ((dir = opendir(fn)) == NULL)
perror("opendir() error");
else {
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] != '.') {
strcpy(path, fn);
strcat(path, "/");
strcat(path, entry->d_name);
if (stat(path, &info) != 0)
fprintf(stderr, "stat() error on %s: %s\n", path,
strerror(errno));
else if (S_ISDIR(info.st_mode))
traverse(path, indent+1);
}
}
closedir(dir);
}
}
main() {
puts("Directory structure:");
traverse("/", 0);
}

Related

Trying to create a code that print absolute path and last modify time of file

WHAT I HAVE TO DO
I have to find, starting from a directory, a file located in one of all directories that have as root the directory passed in input.
Something as shell command find.
INPUT/OUTPUT
Having this in input:
./myfind /home/claudio/Scrivania file.txt
I need something as this in output, absolute path and last modify date ecc:
/home/claudio/Scrivania/SistemiOperativi/file.txt Tue Mar 30 19:51:54 2021
MY CODE
It doesn't print anything.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
#if !defined(NAME_MAX)
#define NAME_MAX 256
#endif
void find(const char* passed_dir_name, const char* passed_file_name) {
if (chdir(passed_dir_name) == -1) {
perror("FATAL ERROR CHANGING DIRECTORY");
exit(EXIT_FAILURE);
}
DIR* current_directory;
if ((current_directory = opendir(".")) == NULL) {
perror("FATAL ERROR OPENING CURRENT WORKING DIRECTORY");
exit(EXIT_FAILURE);
}
char* buf;
if ((buf = calloc(NAME_MAX, sizeof(char))) == NULL) {
perror("FATAL ERROR ALLOCATING MEMORY");
exit(EXIT_FAILURE);
}
struct dirent* dir;
while ((dir = readdir(current_directory)) != NULL) {
struct stat statbuf;
stat(dir->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
if (strncmp(dir->d_name, ".", 1) != 0 && strncmp(dir->d_name, "..", 2) != 0) {
find(dir->d_name, passed_file_name);
}
} else {
if (strncmp(dir->d_name, passed_file_name, strlen(passed_file_name) == 0)) {
if (getcwd(buf, NAME_MAX) == NULL) {
perror("FATAL ERROR");
exit(EXIT_FAILURE);
}
fprintf(stdout, "%s/%s %s", buf, dir->d_name, ctime(&statbuf.st_mtime));
}
}
}
if (closedir(current_directory) == -1) {
perror("FATAL ERROR CLOSING CURRENT WORKING DIRECTORY");
exit(EXIT_FAILURE);
}
chdir("..");
free(buf);
}
int main(int argc, char** argv) {
if (argc != 3) {
fprintf(stderr, "ERROR: RUn as ./myfind directory\n");
exit(EXIT_FAILURE);
}
const char* dir = argv[1];
const char* file = argv[2];
struct stat statbuf;
stat(dir, &statbuf);
if(!S_ISDIR(statbuf.st_mode)) {
fprintf(stderr, "FATAL ERROR: %s IS NOT A DIRECTORY\n", dir);
exit(EXIT_FAILURE);
}
find(dir, file);
exit(EXIT_SUCCESS);
}
Your parentheses are wrong in:
if (strncmp(dir->d_name, passed_file_name, strlen(passed_file_name) == 0))
You need to write:
if (strncmp(dir->d_name, passed_file_name, strlen(passed_file_name)) == 0)
Since strncmp(x, y, 0) will always return 0, the condition is never being met.
But note that there's no point in using strncmp here at all. strncmp is only needed if you don't know that one of your entries is a null terminated string. You have a guarante that d_name is null-terminated, and if passed_file_name is not, then strlen is going to be problematic. You might as well just write strcmp(dir->d_name, passed_file_name).

Trying to create code in C that print all directories starting from a root directory passed

EXAMPLE
Imagine I have a directory called Alpha and I want it as root.
Alpha contains: some files and other two directories Beta and Gamma,
Beta contains: some files and another directory called Theta,
Gamma contains: some files,
Theta contains: some files.
INPUT/OUTPUT
Using input as: ./myfind Alpha
I'll want as output:
Alpha
Beta
Gamma
Theta
(I don't care about the order).
MY CODE
I tried with this code but it doesn't work. I'll want to do a recursive function to do it and i can't use POSIX.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
#if !defined(NAME_MAX)
#define NAME_MAX 256
#endif
int find(const char *passed_dir_name) {
if (chdir(passed_dir_name) == -1) {
perror("FATAL ERROR CHANGING DIRECTORY");
return -1;
}
DIR *current_directory;
if ((current_directory = opendir(".")) == NULL) {
perror("FATAL ERROR OPENING CURRENT WORKING DIRECTORY");
return -1;
}
struct dirent *dir;
while ((dir = readdir(current_directory)) != NULL) {
struct stat statbuf;
stat(dir->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
fprintf(stdout, "%s\n", dir->d_name);
find(dir->d_name);
}
}
if (closedir(current_directory) == -1) {
perror("FATAL ERROR CLOSING CURRENT WORKING DIRECTORY");
exit(EXIT_FAILURE);
}
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "ERROR: Run as ./myfind directory\n");
exit(EXIT_FAILURE);
}
const char *dir = argv[1];
struct stat statbuf;
stat(dir, &statbuf);
if (!S_ISDIR(statbuf.st_mode)) {
fprintf(stderr, "FATAL ERROR: %s IS NOT A DIRECTORY\n", dir);
exit(EXIT_FAILURE);
}
find(dir);
exit(EXIT_SUCCESS);
}
The problem is you change the current directory when you recurse into a subdirectory but you do not change back to the parent directory when returning from the recursive function.
You could add a chdir(".."); at the end of the find function, but it might not work in all cases:
if a directory has more than 2 hard links
if you traverse symbolic links
It is preferable to compute the path of the destination directory for the recursive call to find() by concatenating the passed_dir_name, a / and dir->d_name and avoid changing the current directory.
Here is a modified version of find() for the simplistic approach:
int find(const char *passed_dir_name) {
if (chdir(passed_dir_name) == -1) {
perror("FATAL ERROR CHANGING DIRECTORY");
return -1;
}
DIR *current_directory;
if ((current_directory = opendir(".")) == NULL) {
perror("FATAL ERROR OPENING CURRENT WORKING DIRECTORY");
chdir("..");
return -1;
}
struct dirent *dir;
while ((dir = readdir(current_directory)) != NULL) {
struct stat statbuf;
stat(dir->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
fprintf(stdout, "%s\n", dir->d_name);
find(dir->d_name);
}
}
if (closedir(current_directory) == -1) {
perror("FATAL ERROR CLOSING CURRENT WORKING DIRECTORY");
exit(EXIT_FAILURE);
}
chdir("..");
}

Problem reading directories in C

I am writing a simple C program that receives a directory as an argument and displays the files in this directory and also his subdirectories. I wrote a "recursive" function for doing that. But for an unknown reason, my program fails at the stat function. Here is my program :
#define _POSIX_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
void display_directory(char* path){
DIR* directory = opendir(path);
if( directory == NULL){
printf("opendir failure for %s\n", path);
exit(1);
}
struct dirent* dirent;
struct stat stat_info;
while((dirent = readdir(directory)) != NULL){
printf("[%s]\n", dirent->d_name);
if(stat(dirent -> d_name, &stat_info) == -1){
printf("readdir error for %s\n", dirent->d_name);
exit(1);
}
if(S_ISREG(stat_info.st_mode)){
printf("File: %s \n", dirent -> d_name);
}
if(S_ISDIR(stat_info.st_mode)){
if(strncmp(dirent->d_name, "..",2)){
printf("Directory : %s\n", dirent->d_name);
display_directory(dirent->d_name);
}
}
}
closedir(directory);
}
int main(int argc, char* argv[]){
char* path;
if(argc > 1){
path = argv[1];
} else {
path = ".";
}
display_directory(path);
return EXIT_SUCCESS;
}
For instance, if in my directory A, I have a1, a2, a3 and .., it reads first the .. directory, and when it reads the directory a1, the stat function fails.
Can someone tells me what is not correct with my code.
[EDIT] I included <errno.h> as many of you suggest and after running the program, I have the error Too many open files.
#define _POSIX_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
void display_directory(char* path){
DIR* directory = opendir(path);
if( directory == NULL){
printf("opendir failure for %s --> %s\n", path, strerror(errno));
exit(1);
}
struct dirent* dirent;
struct stat stat_info;
while((dirent = readdir(directory)) != NULL){
printf("[%s]\n", dirent->d_name);
if(stat(dirent->d_name, &stat_info)){
printf("readdir error for %s ---> %s\n", dirent->d_name, strerror(errno));
continue;
}
if(S_ISREG(stat_info.st_mode)){
printf("Fichier : %s \n", dirent->d_name);
}
if(S_ISDIR(stat_info.st_mode)){
if(strncmp(dirent->d_name, "..",2)){
printf("Directory : %s\n", dirent->d_name);
display_directory(dirent->d_name);
}
}
}
closedir(directory);
}
int main(int argc, char* argv[]){
char* path;
if (argc > 2) {
fprintf(stderr, "Usage: %s [directory]\n", argv[0]);
exit(1);
}
path = argv[1];
display_directory(path);
return EXIT_SUCCESS;
}
The output of the program :
[..]
[mykill.c]
readdir error for mykill.c ---> No such file or directory
[.]
Directory : .
[..]
[.]
Directory : .
[..]
[.]
Directory : .
[..]
...
...
Directory : .
opendir failure for . --> Too many open files
mykill.c is a file in the directory that was passed as an argument.
I have a pretty good idea what's wrong, but I want to tell you how to debug this for yourself, first. Change this code ...
if(stat(dirent -> d_name, &stat_info) == -1){
printf("readdir error for %s\n", dirent->d_name);
exit(1);
}
... to read instead ...
if (stat(dirent->d_name, &stat_info)) {
printf("%s: %s\n", dirent->d_name, strerror(errno));
continue;
}
You will need to add to the include list
#include <errno.h>
Run the program again. If you don't see from the output what the problem is, then edit the COMPLETE, UNEDITED output into your question and we'll go from there.
if(S_ISDIR(stat_info.st_mode)){
if( !strcmp(dirent->d_name, ".")) continue;
if( !strcmp(dirent->d_name, "..")) continue;
printf("Directory : %s\n", dirent->d_name);
display_directory(dirent->d_name);
}
You are making stat only with filename (without full path), add full path to the filename or change working directory before calling stat.
Use nftw().

Get only the files included in a directory in c / Ubuntu

I have to create a listing of the files contained inside a specific directory, I have done the code below(part of a bigger programm), but I would like my programm to ignore any possible folders that could be included inside the directory.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main ()
{
DIR *dirptr;
struct dirent *entry;
dirptr = opendir ("synchedFolder");
if (dirptr != NULL)
{
while (entry = readdir (dirptr))
{
if(strcmp(entry->d_name,"..")!=0 && strcmp(entry->d_name,".")!=0)
puts (entry->d_name);
}
(void) closedir (dirptr);
}
else
perror ("ERROR opening directory");
}
If you want to list only files, but no directories, you have to add the following check:
entry->d_type == DT_REG
or
entry->d_type != DT_DIR
There's stat() and lstat() and the return value for stat. In the latter, look out for the S_ISDIR macro.
Short answer is the dirent structure includes the necessary information:
if ( entry->d_type == DT_REG)
Check stat (or lstat)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
/* int main (void){ */
int main (int argc, char **argv){
int i,result=0;
struct stat buf;
/* print_S_I_types(); */
for (i=1; i < argc; i++){
if (lstat(argv[i], &buf) < 0) {
fprintf(stderr, "something went wrong with %s, but will continue\n",
argv[i]);
continue;
} else {
if S_ISREG(buf.st_mode){
printf("argv[%d] is normal file\n",i);
}else {
printf("argv[%d] is not normal file\n",i);
}
}
}
return 0;
}
Working code for listing files (without directories):
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main()
{
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("/home/images")) != NULL)
{
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL)
{
if(ent->d_type!= DT_DIR)
{
printf ("%s\n", ent->d_name);
}
}
closedir (dir);
}
else
{
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
}

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