Hello all, I am currently working on a package manager in C and am at the point where I am trying to check to see if the package is already installed. To do this I am taking the package name(s) as an argument using argv. The working code for doing this as follows:
#include <stdio.h>
#include <sys/stat.h>
#include<dirent.h>
int main(int argc, char *argv[])
{
short i;
struct stat program;
for (i = 1; i < argc; i++) {
if (stat(argv, &program) == 0)
return 0;
else
return 1;
}
}
This works, I have tested it with prints and everything. The issue with this is that it does not check /bin and /sbin, but rather checks the directory it is being run from. So I did some research and wrote a separate .c file to list /bin which is as follows:
#include <stdio.h>
#include <dirent.h>
short open(char *directory)
{
struct dirent *de;
DIR *dr = opendir(directory); /* directory to open */
if (dr == NULL) {
printf("directory could not be opened");
return 0;
}
while ((de = readdir(dr)) != NULL) /* print entries in dr */
printf("%s\n", de->d_name);
closedir(dr);
return 0;
}
int main()
{
open("/bin");
}
this also works. The issue I am having is I can't figure out how to
A) List both /bin and /sbin
B) Check for the program in those directories (this one is the one I really need help with).
Now for checking both I figure I can say basically
if argv isn't found in /bin check /sbin (if more than one is given then check for all of them and if any were found say which were)
If I can get B solved than A should be pretty easy. I just can't for the life of me figure it out, I would love some advice. Thank you for reading.
Edit:
Progress! Oh sweet sweet progress on this issue I have been stuck on for weeks, so after thinking with a clear head I realized my first function checks for the file and my second opens the directory. All I needed to do was combine them, so I did so and got this:
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
struct dirent *de;
DIR *dr = opendir("/bin"); /* directory to open */
short i;
struct stat program;
if (dr == NULL) {
printf("directory could not be opened");
return 0;
}
while ((de = readdir(dr)) != NULL) {
for (i = 1; i < argc; i++) {
if (stat(argv, &program) == 0) {
printf("found\n");
closedir(dr);
}
else {
printf("not found\n");
closedir(dr);
}
}
}
return 0;
}
Now this always prints not found, I am still working on this but am having a hard time debugging it.