FTW does not give "newest" directory - c

I have the following C code:
#include <ftw.h>
#define MAXPATHLEN 100
static time_t createtime = 0;
static char ftwpath[MAXPATHLEN];
[...]
ftw(somepath, get_writedir, 10);
if (ftwpath[0] == '\0') {
//Code assuming that the directory does not exist.
} else {
//Some code handeling
}
That is the method that ftw calls:
int get_writedir(const char *path, const struct stat *sb, int typeflag)
{
if (typeflag == FTW_D && sb->st_ctime > createtime) {
createtime = sb->st_ctime;
strlcpy(ftwpath, path, MAXPATHLEN);
}
return 0;
}
Generally speking this code works to some extend when typeflag is set to FTW_F, not FTW_D. When I do the latter, nothing happens.
When I do the prior: I do not always get the "newest created directory". What am I doing wrong here?

Related

How to list only user provided file names from the directory in C?

I know how to printf all files from the directory,but how i find one specific file in that directory using name provided earlier by user?
#include <dirent.h>
#include <stdio.h>
int main(void)
{
DIR *d;
struct dirent *dir;
char a,b;
printf("Path:(eg.c:/): ");
scanf("%s",&a);
d = opendir (&a);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
From comments:
I would like to know how to implement this in my code because I have never used these functions.
Since you are using Windows, FindFirstFile and FindNextFile can be used to search a directory for a list of filespecs, from there you can simply use strstr to isolate the file you need by comparing the search result with your user's desired filename.
Here is an example that can be modified for your purposes:
#include <stdio.h>
#include <string.h>
#include <windows.h>
void find(char* path,char* file)
{
static int found =0;
HANDLE fh;
WIN32_FIND_DATA wfd;
int i=0;
int j=0;
fh=FindFirstFile(path,&wfd);
if(fh)
{
if(strcmp(wfd.cFileName,file)==0)
{
path[strlen(path)-3]='\0';
strcat(path,file);
FindClose(fh);
return;
}
else
{
while(FindNextFile(fh,&wfd) && found ==0)
{
if(strcmp(wfd.cFileName,file)==0)
{
path[strlen(path)-3]='\0';
strcat(path,file);
FindClose(fh);
found =1;
return;
}
if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
strcmp(wfd.cFileName,"..")!=0 && strcmp(wfd.cFileName,".")!=0)
{
path[strlen(path)-3]='\0';
strcat(path,wfd.cFileName);
strcat(path,"\\*.*");
find(path,file);
}
}
if(found==0)
{
for(i=strlen(path)-1;i>0;i--)
{
if(j==1 && path[i]=='\\')
{
path[i]='\0';
strcat(path,"\\*.*");
break;
}
if(path[i]=='\\')
j=1;
}
}
}
FindClose(fh);
}
}
int main()
{
TCHAR path[512] = "C:\\*.*";
find(path,"notepad.exe");
printf("%s\n",path);
return 0;
}

checking directory paths ends with ".", ".."

I have a programming problem that I hope someone out there can help me with. I am trying to learn C programming for a task at work and I have set myself a little project, which consists of reading down a file tree including all the sub directories obtaining information about each file.
The problem I get is that my program dosen't ignore the directory path ends with either /. or /.. and when it prints all the directories, I want to give space in front of the subdirectories for the readablity.
so the error is occured at this part:
int isDir(const char *parent, char *name) {
struct stat st_buf; // file info
char buf[BUF_SIZE];
if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
return 0;
}
char *path = malloc(strlen(name) + strlen(parent) + 2);
//sprintf(char *buf, const char *format, [arg1],[arg2],...)
sprintf(path, "%s/%s", parent, name);
stat(path, &st_buf); //
return S_ISDIR(st_buf.st_mode); //directory
}
And this is main and list function:
int list(const char *name) {
DIR *dirp = opendir(name);
struct dirent *dentry;
char buf[BUF_SIZE];
while ((dentry = readdir(dirp)) != NULL) {
char *dir_name = dentry->d_name;
printf(" %s\n", dir_name);
//if it's dir, then go into dir
if (isDir(name, dir_name)) { //name : parent, dir_name : child
chdir(dir_name);
getcwd(buf, BUF_SIZE);
list(buf);
}
}
closedir(dirp);
}
int main()
{
list(".");
return 0;
}
The result is like this:
hm1.c
Data
lab1.txt
result1
lab3.txt
.
..
.
..
result2
lab3.txt
.
..
result3
lab3.txt
.
..
a.c
.
..
a.out
result I want to print
hm1.c
Data
lab1.txt
result1
lab3.txt
result2
lab3.txt
result3
lab3.txt
a.c
a.out
Your isDir is returning true/false where it returns false (or zero) if you have . oe .. and then the true/false value of S_ISDIR in other cases
What you really need is the function to return one of 3 values SKIP, isFILE or isDIR and then write your print logic based on that.
You also need to fix your memory leaks
Also note that chdir(dir_name); changes the actual directory of the process, so once you return fromlist within your loop you will no longer be able to open the files or directories that you are looping over (because you are now in a different directory)
This will fix your problems and print the format you want
enum { doSkip, isFile, isDir } testDir(char *path, char *name)
{
struct stat st_buf;
if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
return doSkip;
}
stat(path, &st_buf);
if (S_ISDIR(st_buf.st_mode))
return isDir;
return isFile;
}
void list(const char *path, int indentlevel)
{
DIR *dirp = opendir(path);
struct dirent *dentry;
char buf[10000]; // Lets just make the buffer sufficently big for this example
if (!dirp) {
printf("%*sNo access\n",indentlevel,"");
return;
}
while ((dentry = readdir(dirp)) != NULL) {
sprintf(buf,"%s/%s", path, dentry->d_name);
switch (testDir(buf,dentry->d_name)) {
case doSkip:
/* do nothing */
break;
case isDir:
printf("%*s%s:\n",indentlevel,"",dentry->d_name);
list(buf,indentlevel+4);
break;
case isFile:
printf("%*s%s\n",indentlevel,"",dentry->d_name);
break;
}
}
closedir(dirp);
}
int main()
{
list(".", 0);
return 0;
}
Another way to do it, if you're willing to go to C++, is to use std::experimental::filesystem, also (mostly) known as Boost.Filesystem. With that, you would do something like:
#include <experimental/filesystem> // Could substitute <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <iostream>
using namespace std::experimental;
int main(int argc, char *argv[])
{
const auto path = filesystem::path{ argc > 1 ? argv[1] : "." };
if( filesystem::is_directory(path) )
{
std::cout << path << " is a directory containing:\n";
for( const auto& entry : boost::make_iterator_range( filesystem::recursive_directory_iterator{path}, {} ) )
{
std::cout << entry << "\n";
}
}
}
See it run here. Note that the directory iterators automatically skip . and ...

working with directories in POSIX with C

I will go ahead and say this is a homework assignment for an intro to Linux class. I would not be posting it without extensive attempts on my own, and seeing as I am a distance student this semester, I cannot make it to campus for tutoring. I need some help finding out what the issue is.
Essentially the assignment asks us to make a program that serves the same basic function as the pwd command in POSIX, to show the absolute path for the current directory. We are to use three functions along with main. We are not to use the getcwd command as well. I'll list them and their purpose
inum_to_filename: Accepts three arguments (inode number to translate, a pointer to a buffer where the name is written, and the size of the buffer). Returns nothing. It is to:
Open the current directory,
Read the first directory entry,
If the inode of the current directory matches the one passed in, copy name to buffer and return.
Otherwise read the next directory entry and repeat the previous step.
filename_to_inum: Accepts one argument (a char * representing the filename). It returns the corresponding inode number. It is to:
Read the information from the files inode into a structure in memory.
If there is any problem, display the appropriate error.
Return the inode number from the structure.
display_path: Accepts one argument (inode from the current working directory). It returns nothing. It is to:
Create an array of characters to use as a buffer for the name of the directory.
Get the inode for the parent directory using filename_to_inode.
If the parent inode is equal to the current inode, we have reached root and can return.
Otherwise, change to the parent directory and use inum_to_filename to find the name for the inode that was passed into the function. Use the buffer from step 1 to store it.
Recursively call display_path to display the absolute path.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void inum_to_filename (int inode_arg, char *pathBuffer, int size_arg) {
DIR *dir_ptr = opendir(".");
struct dirent *dirent_ptr = readdir(dir_ptr);
int counter = 0;
while (counter != 1) {
if (inode_arg == dirent_ptr->d_ino) {
strcat(pathBuffer, "/");
strcat(pathBuffer, dirent_ptr->d_name);
counter = counter + 1;
return;
} else {
dirent_ptr = readdir(dir_ptr);
}
}
closedir(dir_ptr);
}
int filename_to_inum (char *src) {
int res = 0;
struct stat info;
int result = stat(src, &info);
if (result != 0) {
fprintf(stderr, "Cannot stat ");
perror(src);
exit(EXIT_FAILURE);
} else {
res = info.st_ino;
}
return res;
}
void display_path (int ino_src) {
int bufSize = 4096;
char pathBuffer[bufSize];
int ino_prnt = filename_to_inum("..");
if (ino_src == ino_prnt) {
//print for test
inum_to_filename(ino_src, pathBuffer, bufSize);
printf("%s", pathBuffer);
return;
} else {
//print for test
chdir("..");
inum_to_filename(ino_src, pathBuffer, bufSize);
display_path(ino_prnt);
printf("%s", pathBuffer);
}
}
int main (int argc, char *argv[]) {
int c_ino = filename_to_inum(".");
display_path(c_ino);
printf("\n");
}
As of right now it is displaying "/./MyName" with MyName being my personal named directory on the server. It is the directory I am running the program from. When using pwd I return "/home/MyName". I'm not really sure what my next step to getting the absolute path correct is.
The code is mostly set up to print one name at a time in the correct order, so the primary problem is the use of strcat() rather than strcpy(). Also, detecting when you're in the root directory at the start is important; if you don't, you can end up with /. or something similar (depending on exactly how you coordinate the printing) when the current directory is the root directory.
This version of your code has:
Squished the loop in inum_to_filename(), but also added error reporting. Remember, a process can be run in a directory which it does not have permission to get to (it requires a setuid program, usually — although permissions could be changed after the program is launched). In that case, it may fail to open .. (or .).
Lost variable count; it wasn't serving a useful purpose. Using the assign-and-test idiom allows the code to contain a single call to readdir().
Use strcpy() instead of strcat().
Use type ino_t to store inode numbers. Use size_t for sizes.
Reduce number of intermediate variables in filename_to_inum().
Note that the code in the if (ino_src == ino_prnt) statement body is for the root directory; in the absence of the testing print, it would do nothing.
Note that the printing in the else part is a major part of the operations, not just test printing.
Error check chdir("..");
Detect root in main().
Observe that this code is not directly suitable for rewriting into a function because it changes the process's current directory to / when it succeeds.
Revised code:
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static void inum_to_filename(ino_t inode_arg, char *pathBuffer, size_t size_arg)
{
assert(size_arg > 0);
DIR *dir_ptr = opendir(".");
if (dir_ptr == 0)
{
fprintf(stderr, "Failed to open directory '.' (%d: %s)\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
struct dirent *dirent_ptr;
while ((dirent_ptr = readdir(dir_ptr)) != 0)
{
if (inode_arg == dirent_ptr->d_ino)
{
if (strlen(dirent_ptr->d_name) >= size_arg)
{
fprintf(stderr, "File name %s too long (%zu vs %zu max)\n",
dirent_ptr->d_name, strlen(dirent_ptr->d_name), size_arg);
exit(EXIT_FAILURE);
}
strcpy(pathBuffer, dirent_ptr->d_name);
break;
}
}
closedir(dir_ptr);
}
static ino_t filename_to_inum(char *src)
{
struct stat info;
if (stat(src, &info) != 0)
{
fprintf(stderr, "Cannot stat ");
perror(src);
exit(EXIT_FAILURE);
}
return info.st_ino;
}
static void display_path(ino_t ino_src)
{
size_t bufSize = 4096;
char pathBuffer[bufSize];
ino_t ino_prnt = filename_to_inum("..");
if (ino_src == ino_prnt)
{
// print for test
inum_to_filename(ino_src, pathBuffer, bufSize);
printf("%s", "(root): /\n");
}
else
{
// print for real
if (chdir("..") != 0)
{
fprintf(stderr, "Failed to chdir to .. (%d: %s)\n",
errno, strerror(errno));
}
inum_to_filename(ino_src, pathBuffer, bufSize);
display_path(ino_prnt);
printf("/%s", pathBuffer);
}
}
int main(void)
{
ino_t c_ino = filename_to_inum(".");
ino_t r_ino = filename_to_inum("/");
if (r_ino == c_ino)
putchar('/');
else
display_path(c_ino);
printf("\n");
}
There are undoubtedly other ways to fix this.
Caveat: this is giving me some grief when working in /Volumes/CRUZER/Sub-Directory which is a memory stick. It fails to find the inode (1, which is surprising) when scanning /Volumes, and I've not worked out why. One of my programs — a getpwd implementation — is working fine; another is having a different problem. I expect I'll get to the bottom of it all. Testing on Mac OS X 10.10.5 with GCC 5.1.0.
this is really nice assignment :).
I read and tried your code, and it is almost correct. There were two small issues which were causing the incorrect behaviour.
First issue
When display_path reaches the root folder you don't need to call inum_to_filename and print the name of the folder because you have already printed the first folder of the path in the previous iteration. This prevents your code from showing a "./" in the beginning of the path.
That is, the if condition becomes:
if (ino_src == ino_prnt) {
return;
} else {
chdir("..");
inum_to_filename(ino_src, pathBuffer, bufSize);
display_path(ino_prnt);
printf("%s", pathBuffer);
}
Second Issue:
You're not initializing propertly the buffer where you save the name of the directory. This causes random values to be displayed. To solve this issue you can just set the initial value of the buffer to zero by using memset.
void inum_to_filename (int inode_arg, char *pathBuffer, int size_arg) {
DIR *dir_ptr = opendir(".");
struct dirent *dirent_ptr = readdir(dir_ptr);
int counter = 0;
memset(pathBuffer, 0, size_arg);
while (counter != 1) {
...
}
closedir(dir_ptr);
}
Full code working :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void inum_to_filename (int inode_arg, char *pathBuffer, int size_arg) {
DIR *dir_ptr = opendir(".");
struct dirent *dirent_ptr = readdir(dir_ptr);
int counter = 0;
memset(pathBuffer, 0, size_arg);
while (counter != 1) {
if (inode_arg == dirent_ptr->d_ino) {
strcat(pathBuffer, "/");
strcat(pathBuffer, dirent_ptr->d_name);
counter = counter + 1;
return;
} else {
dirent_ptr = readdir(dir_ptr);
}
}
closedir(dir_ptr);
}
int filename_to_inum (char *src) {
int res = 0;
struct stat info;
int result = stat(src, &info);
if (result != 0) {
fprintf(stderr, "Cannot stat ");
perror(src);
exit(EXIT_FAILURE);
} else {
res = info.st_ino;
}
return res;
}
/*
- Create an array of characters to use as a buffer for the name of the directory.
- Get the inode for the parent directory using filename_to_inode.
- If the parent inode is equal to the current inode, we have reached root and can return.
- Otherwise, change to the parent directory and use inum_to_filename to find the name for
the inode that was passed into the function. Use the buffer from step 1 to store it.
- Recursively call display_path to display the absolute path.
*/
void display_path (int ino_src) {
int bufSize = 4096;
char pathBuffer[bufSize];
int ino_prnt = filename_to_inum("..");
if (ino_src == ino_prnt) {
return;
} else {
chdir("..");
inum_to_filename(ino_src, pathBuffer, bufSize);
display_path(ino_prnt);
printf("%s", pathBuffer);
}
}
int main (int argc, char *argv[]) {
int c_ino = filename_to_inum(".");
display_path(c_ino);
printf("\n");
}
Output :
ubuntu#ubuntu-VirtualBox:~/dev$ vi pwd.c
ubuntu#ubuntu-VirtualBox:~/dev$ gcc pwd.c
ubuntu#ubuntu-VirtualBox:~/dev$ ./a.out
/home/ubuntu/dev
ubuntu#ubuntu-VirtualBox:~/dev$ pwd
/home/ubuntu/dev
ubuntu#ubuntu-VirtualBox:~/dev$

How to get total size of a folder in C with recursivity?

All the folders have the size 4096 B.
How do I get the total size of a folder with all the file size inside?
For example:
> Dir1 (4096)
> -- File1.txt (100)
> -- Dir 2 (4096)
> ---- File2.txt (100)
When I try to get the size of Dir1, it gives me 4096.
The expected answer I wish to get is 8392
Another example:
DirA (4096)
-- FileA (100)
-- FileB (100)
The total should be 4296
I'm trying to figure out the algorithm but I can't find a way to detect if it's a folder or not. Sorry for the "vulgar" code below...
DIR *dir;
struct dirent *dp;
struct stat fileStat;
int getTotalDirSize()
{
while()
{
if(/*Detect Folder/Directory*/)
{
totalSize += 4096;
getTotalDirSize();
}
else
{
totalSize += fileSize;
}
}
return totalSize;
}
Note: I'm using the struct stat to get the size and the file/folder name.
Its working using with stat but only you have to do is give complete path to the stat like in your example Dir1->4096B then if you want to know size of the File1.txt use in stat like this:
strcpy(str,Dir1); //str is a string
strcat(str,"/");
strcat(str,filename);
Then use str in stat to get size of that file. I think here you have to use dirent structure and DIR for folder and its contents.
For finding folder use d_type = 4 for dirent structure pointer. For recursive action put all in one separate function and call it recursively until folder search completes.
struct stat buf;
DIR *dptr;
struct dirent *sdir;
int size=0;
char str[100];
dptr=opendir(folder);
while(sdir=readdir(dptr))
{
if(sdir->d_type==4)
{
if(sdir->d_name[0]!='.')
{
stat(sdir->d_name,&buf);
size=buf.st_size;
pf("size=%d\n",size);
}
}
else
{
strcpy(str,folder);
strcat(str,"/");
strcat(str,sdir->d_name);
stat(str,&buf);
size+=buf.st_size;
pf("size=%d\n",size);
}
}
I was just searching for a solution to this same problem when I encountered this thread and some others here on SO dealing with equal or similar problems (I found at the end 3 different codes aimed to calculate the total size of a folder with pure C). Unfortunately none of them worked by themselves or were incomplete, so I had to improve them (merging one into the other) and I came to the following complete and working code-and-example (should be put inside a main.c file, the exact folder changed and then just run). I hope it helps!
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <stdint.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
int readFolderSize(int* totalSize, char* folder)
{
char fullPath[256];
struct dirent *dirData;
struct stat buffer;
int exists;
DIR *poDir;
int resp = EXIT_SUCCESS;
poDir = opendir(folder);
if (poDir == NULL)
{
perror("general_getFolderSize: poDir fail!");
return EXIT_FAILURE;
}
while ((dirData = readdir(poDir)))
{
if (dirData == NULL)
{
const unsigned int err = errno;
fprintf(stderr, "general_getFolderSize: Failed in readdir (%u)\n",err);
resp = EXIT_FAILURE;
continue;
}
//
if (dirData->d_type == DT_DIR)
{
if (dirData->d_name[0] != '.')
{
//printf("general_getFolderSize: Is a directory: %s\n", dirData->d_name);
strcpy(fullPath,folder);
strcat(fullPath,"/");
strcat(fullPath,dirData->d_name);
//printf("general_getFolderSize: Accessing dir: %s\n", fullPath);
if (readFolderSize(totalSize,fullPath) == EXIT_FAILURE)
resp = EXIT_FAILURE;
}
}
else
{
strcpy(fullPath,folder);
strcat(fullPath,"/");
strcat(fullPath,dirData->d_name);
exists = stat(fullPath,&buffer);
if (exists < 0)
{
const unsigned int err = errno;
fprintf(stderr, "general_getFolderSize: Failed in stat (file) %s: %u\n", fullPath,err);
resp = EXIT_FAILURE;
continue;
}
else
{
(*totalSize) += buffer.st_size;
//printf("general_getFolderSize: Item size (file) (%s): %d\n",fullPath,(int)buffer.st_size);
}
}
}
closedir(poDir);
return resp;
}
/*!
* \brief general_getFolderSize returns the size of a folder in bytes.
* \param folder is the name of the folder (preferentially without a '/' at the end)
* \param totalSize is a pointer where the result value is given
* \return
*/
int general_getFolderSize(char* folder, int* totalSize)
{
printf("general_getFolderSize: Start\n");
//
if (readFolderSize(totalSize,folder) == EXIT_FAILURE)
{
perror("general_getFolderSize: Call to readFolderSize failed!");
return EXIT_FAILURE;
}
//
printf("general_getFolderSize: Stop\n");
return EXIT_SUCCESS;
}
int main()
{
int folderSize;
if (general_getFolderSize("/home/maiquel/Documents/TEMP/maindir",&folderSize) == EXIT_FAILURE)
{
printf("Error reading folder size!");
}
else
{
printf("Folder size: %d b (%d kb / %d Mb)\n", folderSize, folderSize/1024, folderSize/(1024 * 1024));
}
return EXIT_SUCCESS;
}
P.s.: Although I'm aware that EXIT_SUCCESS and EXIT_FAILURE are not supposed to be used as function return values, I preferred to do so instead of creating new defines in the name of code simplicity.

Search for a file in $PATH on Linux in C

I would like to test whether GNUPlot is installed on the system on which my program is running.
For that, I figured I'll test for the existence of the gnuplot executable in the user's install locations through stat() call.
However, I don't know how to read the $PATH environment variable in C so I can test for the existence of the file in those locations.
Use the getenv() function.
char *paths = getenv("PATH");
To loop through the parts of the column-separated list of paths, use strchr():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *dup = strdup(getenv("PATH"));
char *s = dup;
char *p = NULL;
do {
p = strchr(s, ':');
if (p != NULL) {
p[0] = 0;
}
printf("Path in $PATH: %s\n", s);
s = p + 1;
} while (p != NULL);
free(dup);
Use getenv() to inspect the value of a particular environment variable.
To read the PATH environment variable, use getenv("PATH").
However, if you just want to run gnuplot if it's available, and perform some fallback action if it's not, then you should just try to run it (e.g. with fork and execvp or posix_spawnp) and handle the failure case.
Let which do the work for you
if (system("which gnuplot"))
/* not installed or not in path or not executable or some other error */
If you need the full path for some reason, run which with popen.
Or run gnuplot with some flag which makes it return immediately with 0 */
if (system("gnuplot --version"))
/* not installed ... */
I had a similar need and resolved it by copying libc execvp code source. I did in the most cross platform I could think of(I have no guatanty and tested just on linux). If it's not such a matter to you and you care about performances, you should use acess or _acess. Note that there is no error check whatsoever and it will just return NULL or a founded openable file in path.
The accepted answer is sometime not acceptable, when you are willing to run the same small binary over and over, redoing the path search every time by calling execvp can be non negligable overhead.
So here is the code and associated tests, you will be mainely interested in the search_in_path_openable_file function.
.h file:
bool is_openable_file(char* path);
/*Return true if path is a readable file. You can call perror if return false to check what happened*/
char* search_in_path_openable_file(char* file_name);
/*Search into PATH env variable a file_name and return the full path of the first that is openable, NULL if not in path*/
char* search_executable(char* file_name);
/*Search file, if not openable and not absolute path(contain /), look for opennable file in the path. If nothing is openable, return NULL. If something is openable, return it as it is (not guaratented to have a full path, but garatanted to be openable)*/
.c file:
#include "file_info.h"
#include <stdio.h>
#include <string.h> //strcpy
/*I wanted to do a really cross platform way. access or _acess may be better*/
bool is_openable_file(char *path) {
FILE *fp = fopen(path, "r");
if (fp) {
// exists
fclose(fp);
return true;
}
return false;
}
bool is_openable_file_until(char *path_begin, size_t until) {
char old = path_begin[until];
path_begin[until] = 0;
bool res = is_openable_file(path_begin);
path_begin[until] = old;
return res;
}
/*You may thinks that libc would have done this function and use it to implement execp function family, but you would be wrong. They just hardcoded the search in every execp function. Unbelievable.
*
* So this function is a modification of their execvp function.
*
* */
char* search_in_path_openable_file(char* file){
char *path = getenv("PATH");
if (path == NULL)
return NULL;
size_t pathlen = strlen(path);
size_t len = strlen(file) + 1;
int total_max_size=pathlen + len;
char* buf=malloc(sizeof(char)*total_max_size);
if (*file == '\0') {
return NULL;
}
char *name, *p;
/* Copy the file name at the top. */
name = memcpy(buf + pathlen + 1, file, len);
/* And add the slash. */
*--name = '/';
p = path;
do {
char *startp;
path = p;
//Let's avoid this GNU extension.
//p = strchrnul (path, ':');
p = strchr(path, ':');
if (!p)
p = strchr(path, '\0');
if (p == path)
/* Two adjacent colons, or a colon at the beginning or the end
of `PATH' means to search the current directory. */
startp = name + 1;
else
startp = memcpy(name - (p - path), path, p - path);
/* Try to execute this name. If it works, execv will not return. */
if (is_openable_file(startp))
return startp;
} while (*p++ != '\0');
/* We tried every element and none of them worked. */
return NULL;
}
char* search_executable(char* file_name){
if (is_openable_file(file_name)){//See realpath manual bug. Watch out
return file_name;
}
if (strchr (file_name, '/') != NULL) //Don't search when it contains a slash.
return NULL;
return search_in_path_openable_file(file_name);
}
tests (As you see I did not test a lot this function, there may exist some problem, use at your risk):
#include "file_info.h"
#include "munit.h"
#include <stdbool.h>
#include <unistd.h>
static void generate_search_executable(char* test_str, char* expected){
char* res= search_executable(test_str);
if (res==NULL)
munit_assert_ptr(expected,==,NULL );
else
munit_assert_string_equal(expected,res);
}
static void generate_openable(char* test_str, bool expected){
bool res= is_openable_file(test_str);
munit_assert_true(expected==res);
}
static void generate_path_search(char* test_str, char* expected_res){
char* res= search_in_path_openable_file(test_str);
if (res==NULL)
munit_assert_ptr(expected_res,==,NULL );
else
munit_assert_string_equal(expected_res,res);
}
//TODO do for other platform, better test would also set path to a custom folder that we control
#define EXISTING_FILE_NOT_IN_PATH "/usr/include/stdlib.h"
#define EXISTING_FILE_IN_PATH "ls"
#define EXISTING_FILE_IN_PATH_FULL "/bin/ls"
#define NOT_EXISTING_FILE "/usrarfzsvdvwxv/ixvxwvnxcvcelgude/ssdvtdbool.h"
int main() {
generate_openable(EXISTING_FILE_IN_PATH, false);
generate_openable(EXISTING_FILE_NOT_IN_PATH, true);
generate_openable(NOT_EXISTING_FILE, false);
generate_path_search(EXISTING_FILE_IN_PATH, EXISTING_FILE_IN_PATH_FULL);
generate_path_search(NOT_EXISTING_FILE, NULL);
generate_path_search(EXISTING_FILE_NOT_IN_PATH, NULL);
generate_search_executable(EXISTING_FILE_IN_PATH, EXISTING_FILE_IN_PATH_FULL);
generate_search_executable(NOT_EXISTING_FILE, NULL);
generate_search_executable(EXISTING_FILE_NOT_IN_PATH, EXISTING_FILE_NOT_IN_PATH);
generate_search_executable("", NULL );
//test current folder existence(maybe it just depend on path containing .,I am not sure, in that case we should remove thoses tests
generate_search_executable("file_info_test", "file_info_test" );
}
To build on one of the previous answers, you can use getenv to get the contents of PATH and then iterate over its components. Instead of using strchr you can use strsep:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
bool exists(const char fname[])
{
return access(fname, F_OK | X_OK) != -1;
}
bool find_in_path(const char name[], char *fullpath, size_t sz) {
char *paths = strdup(getenv("PATH"));
char *tmp = paths; // to use in free
const char *item;
bool found = false;
while ((item = strsep(&paths, ":")) != NULL) {
snprintf(fullpath, sz, "%s/%s", item, name);
if (exists(fullpath)) {
found = true;
break;
}
}
free(tmp);
return found;
}
int main() {
char fullpath[512];
bool found = find_in_path("uname", fullpath, sizeof(fullpath));
if (found) {
printf("found: %s\n", fullpath);
}
return 0;
}
Using C++17 to get a vector of path elements.
% a.out ls
/bin/ls
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
using namespace std;
vector<string> get_paths (string str)
{
vector<string> result;
while(!str.empty())
{
if (auto pos { str.find_first_of (':') }; pos == string::npos)
{
result.push_back(str);
break;
}
else
{
result.emplace_back(str.substr(0, pos));
str.erase(0, pos + 1);
}
}
return move(result);
}
bool exist(const string& fname, int perm=F_OK) { return access(fname.c_str(), perm) == 0; }
int main (int argc, char *argv[])
{
auto result { get_paths(getenv("PATH")) };
for (auto pp : result)
{
string npath { pp };
if (*npath.rbegin() != '/')
npath += '/';
npath += argv[1];
if (exist(npath))
cout << npath << endl;
}
return 0;
}

Resources