Directories being found but not being recognized as directories - c

I am using the stat.h header and stat() to read and list files and directories in a directory. I've tried my code with different preset directories to see the result and print the corresponding type of the entry and so far in each test the code shows the current directory and 2 sub directories as directories but shows the other directories as files despite having the correct path listed alongside it
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <locale.h>
#include <sys/stat.h>
#include <wchar.h>
extern int errno;
int main(int argc, char *argv[]) {
setlocale(LC_ALL,"Turkish");
DIR* dp;
struct dirent dirp;
char test[9999];
getcwd(test,9999);
printf("FOLDERMAIN:%s\n",test);
dp=opendir(".");
searchDirectoryForString(dp,"Mat",test);
return 0;
}
void searchDirectoryForString(DIR* dp,char* str,char* directoryname)
{
int lineno=1,num=0;
FILE* fp;
struct dirent *file;
char temp[99999];
char buf[99999];
char *rpath;
rpath = calloc(99999,1);
char path[99999];
char* temppath;
temppath = calloc(99999,1);
int count = 0;
char dirhold[100];
char* dot;
int line_num = 1;
int find_result=0;
static int check=0;
DIR* fdp;
if(dp==NULL)
{
printf("cant open");
}
struct stat filestat;
while (file=readdir(dp)) {
stat(file->d_name,&filestat);
//printf("%s\n",file->d_name);
if(strcmp(file->d_name,"..")==0||(strcmp(file->d_name,".")==0))
continue;
if ( S_ISDIR(filestat.st_mode))
{
check++;
printf("\n CHECK: %d\n",check);
if(check!=1)
{
strcpy(temppath,directoryname);
printf("temp:%s\n",directoryname);
strcat(directoryname,"\\");
strcat(directoryname,file->d_name);
dot = strrchr(directoryname, '\\');
strcpy(dirhold,dot);
printf("DIR: %s\n",dirhold);
printf("%s KLASÖR\n",directoryname);
chdir(directoryname);
dp=opendir(directoryname);
if(dp==NULL)
{
printf("2\n");
}
strcat(temppath,dirhold);
searchDirectoryForString(dp,str,temppath);
}
else{
strcpy(path,directoryname);
strcat(directoryname,"\\");
strcat(directoryname,file->d_name);
dot = strrchr(directoryname, '\\');
strcpy(dirhold,dot);
printf("DIR: %s\n",dirhold);
printf("%s FOLDER\n",directoryname);
chdir(directoryname);
dp=opendir(directoryname);
if(dp==NULL)
{
printf("2\n");
}
strcat(path,dirhold);
searchDirectoryForString(dp,str,path);
}
}
else
{
snprintf(buf,99999,"%s",directoryname);
strcat(buf,"\\");
//strcat(directoryname,dirhold);
strcat(buf,file->d_name);
printf("%s FILE \n",buf);
//Close the file if still open.
if(fp) {
fclose(fp);
strcpy(rpath," ");
}
}
}
}
}
I tried my best to produce an MCVE below. One new thing i noticed is if i add another folder to a preset folder it is not recognized as a folder. If i add a folder to a folder which is one of the recognized folders it is also recognized as a folder(nested folder) the issue is most likely caused by the stat function so wrote another function for it to be able to seen more clearly as its in its own scope. Im using devc++ as my IDE.
#include <locale.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <wchar.h>
int main(int argc, char *argv[]) {
setlocale(LC_ALL,"Turkish");
DIR* dp;
struct dirent dirp;
char test[9999];
getcwd(test,9999);
printf("FOLDERMAIN:%s\n",test);
dp=opendir(".");
listDir(dp,test);
return 0;
}
int isDir(const char *name) {
struct stat fileStat;
return !stat(name, &fileStat) && S_ISDIR(fileStat.st_mode);
}
void listDir(DIR* dp,char* directoryname)
{
struct dirent *file;
char buf[99999];
char* temppath;
temppath = calloc(99999,1);
int count = 0;
char dirhold[100];
char* dot;
int line_num = 1;
int find_result=0;
static int check=0;
char* dir;
DIR* fdp;
if(dp==NULL)
{
printf("cant open");
}
while (file=readdir(dp)) {
//printf("%s\n",file->d_name);
if(strcmp(file->d_name,"..")==0||(strcmp(file->d_name,".")==0))
continue;
if (isDir(file->d_name))
{
check++;
printf("\n CHECK: %d\n",check);
strcpy(temppath,directoryname);
printf("temp:%s\n",directoryname);
strcat(directoryname,"\\");
strcat(directoryname,file->d_name);
dot = strrchr(directoryname, '\\');
strcpy(dirhold,dot);
printf("DIR: %s\n",dirhold);
printf("%s FOLDER\n",directoryname);
chdir(directoryname);
dp=opendir(directoryname);
if(dp==NULL)
{
printf("2\n");
}
strcat(temppath,dirhold);
listDir(dp,temppath);
}
else
{
snprintf(buf,99999,"%s",directoryname);
strcat(buf,"\\");
strcat(buf,file->d_name);
printf("%s FILE\n",buf);
}
}
}

This is my code that does more or less what you want. It is also available in my SOQ (Stack Overflow Questions) repository on GitHub as file dirlist43.c in the src/so-7406-2431 sub-directory.
What went wrong in the MCVE code?
There were a fairly large number of problems, including:
Not much error checking for failed calls.
Changing directory with changing back correctly.
No debug code to help determine what is going wrong.
Too many places where opendir() was called.
Too many places where the result of opendir() was checked — one of them in a different function from where the call was made.
Missing headers.
Unused variables.
Not reporting errors on stderr.
Confusion about directoryname vs temppath.
Sequencing of chdir() calls worked downwards, once. But there was no code to change back after finishing a directory.
Missing closedir() — I ran out of file descriptors when run on a directory with about 3000 sub-folders.
More debatable: I've used snprintf() or printf() to concatenate strings. For raw performance, you may find that strcpy() and strcat() are quicker, but using strcat() can slow things down as it scans from the start of the string each time. Clever code determines the length of the string so that you can copy each time you append, but the Standard C functions aren't helpful for that.
And notes from another comment:
Note that using chdir() is error prone — doubly so if there are symlinks lurking around — and should be avoided when possible. (This was an accurate comment.)
You have a large number of occurrences of 99999 (and some occurrences of 9999); there should be a macro (or enumeration constant) for that value.
On Unix systems, you must #include <errno.h> and should never declare extern int errno; because errno is typically not a simple variable but rather an expression that evaluates to a per-thread int value. I think the same is true on Windows.
Other solutions
In a comment, I noted that:
If you were coding on a Unix (POSIX) system, it would be an odds-on bet that the problem and the fixes are described in stat() error "no such file or directory when file name is returned by readdir(). Even on Windows, you are likely to be running into similar problems. However, there are Windows-specific APIs to process directories that could be used instead of readdir().
Since your MCVE code uses Windows-style \ path separators but compiles, the majority of the advice in that question is valid. Note that POSIX provides some functions — fstatat() and dirfd() — that avoid messing around with chdir(). This is advantageous, especially in threaded programs as chdir() changes directory for all threads at the same time, which is apt to cause chaos if the different threads are accessing files in different directories identified by relative rather than absolute pathnames.
Code: dirlist43.c
#include <dirent.h>
#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef UNIX
#define DIRSEP_STR "/"
#define DIRSEP_CHR '/'
#else
#define DIRSEP_STR "\\"
#define DIRSEP_CHR '\\'
#endif
#define PATH_LEN 99999
extern void listDir(const char *directoryname);
extern int isDir(const char *name);
int main(void)
{
setlocale(LC_ALL, "Turkish");
char pwd[PATH_LEN];
getcwd(pwd, sizeof(pwd));
printf("FOLDERMAIN: %s\n", pwd);
listDir(pwd);
return 0;
}
int isDir(const char *name)
{
struct stat fileStat;
int rc = stat(name, &fileStat) == 0 && S_ISDIR(fileStat.st_mode);
#ifdef DEBUG
printf("%s(): %d [%s]\n", __func__, rc, name);
#endif /* DEBUG */
return rc;
}
#ifdef DEBUG
static void chk_pwd(const char *tag)
{
char pwd[PATH_LEN];
if (getcwd(pwd, sizeof(pwd)) == 0)
{
int errnum = errno;
fprintf(stderr, "%s(): getcwd() failed: %d %s\n",
__func__, errnum, strerror(errnum));
exit(1);
}
printf("PWD: %s [%s]\n", tag, pwd);
}
#else
#define chk_pwd(tag) ((void)0)
#endif /* DEBUG */
static void set_pwd(const char *directoryname)
{
#ifdef DEBUG
printf("CHDIR 1: [%s]\n", directoryname);
#endif /* DEBUG */
if (chdir(directoryname) != 0)
{
int errnum = errno;
fprintf(stderr, "%s(): chdir(%s) failed: %d %s\n",
__func__, directoryname, errnum, strerror(errnum));
exit(1);
}
chk_pwd("CHDIR 1");
}
void listDir(const char *directoryname)
{
#ifdef DEBUG
static int level = 0;
#endif /* DEBUG */
static int check = 0;
#ifdef DEBUG
printf("-->> %s() level %d (%s)\n", __func__, ++level, directoryname);
#endif /* DEBUG */
DIR *dp = opendir(directoryname);
if (dp == NULL)
{
perror(directoryname);
return;
}
set_pwd(directoryname);
struct dirent *file;
while ((file = readdir(dp)) != NULL)
{
if (strcmp(file->d_name, "..") == 0 || (strcmp(file->d_name, ".") == 0))
continue;
if (isDir(file->d_name))
{
printf("CHECK: %d\n", ++check);
char temppath[PATH_LEN];
snprintf(temppath, sizeof(temppath), "%s%s%s",
directoryname, DIRSEP_STR, file->d_name);
printf("FOLDER: %s\n", temppath);
chk_pwd("Before recursion");
listDir(temppath);
set_pwd(directoryname);
chk_pwd("After recursion");
}
else
{
printf("FILE: %s%s%s\n", directoryname, DIRSEP_STR, file->d_name);
}
}
closedir(dp);
#ifdef DEBUG
printf("<<-- %s() level %d (%s)\n", __func__, level--, directoryname);
#endif /* DEBUG */
}
It can be compiled with -DUNIX if you work on a POSIX-like system where slash / is used to separate path components, or without if you work on a Windows-like system where backslash \ is used. It can be compiled with -DDEBUG to get copious extra debugging output.
The makefile is configured for Unix — the code was tested on a MacBook Pro running macOS Big Sur 11.7.

Related

Trying to write every file name, location and modification time, including subdirectories in c

Ok, so the goal is to pick a directory, look inside of it, and write the location followed by the modification date on a text file. If a directory is encountered within, it should open it and restart the search.
For now, the function "regarder" alone works quite well, but when trying to add the search in the subdirectories, that's where the problem begins
I know the detection of a directory works, and it seems to enter the regarder_dir function, but neither prints the names or writes in the file
Apologies for my potentially bad use of pointers, I have a bad time grasping how they work
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
void ecrire(char * s);
void regarder(char * loc);
char regarder_dir(char * loc);
int main(void) {
/*my main where i put where i want the search to begin */
char localisation[10000]="C:\\Users\\ltonn\\Documents";
regarder(localisation);
return(0);
}
/*a function whose role is to write in the .txt file */
void ecrire(char * s){
FILE * fichiertexte;
fichiertexte = fopen(".\\liste.txt","w");
fprintf(fichiertexte,s);
fclose(fichiertexte);
}
/*the first called function which will return nothing but will write in the .txt file */
void regarder(char * loc){
DIR *d;
struct dirent *dir;
char contenu[10000];
char position[1000];
char modification[20];
char surcontenu[10000];
char souscontenu[10000];
struct stat attrib;
d = opendir(loc);
strcpy(position, loc);
if (d) {
while ((dir = readdir(d)) != NULL) {
strcpy (contenu,dir->d_name);
strcat(position,"\\");
strcat(position,contenu);
stat(position,&attrib);
strftime(modification, 20, "%H:%M:%S %d-%m-%y", localtime(&(attrib.st_mtime)));
if(S_ISDIR(attrib.st_mode)){
strcpy(souscontenu, regarder_dir(position));
strcat(surcontenu, souscontenu);
}
strcat(position,"\n");
strcat(position,modification);
strcat(position,"\n \n");
strcat(surcontenu,position);
strcpy(position,loc);
modification[0]=0;
}
closedir(d);
}
printf("%s",surcontenu);
ecrire(surcontenu);
}
/* the loop that should return the result of regarder for the directory at the position*/
char regarder_dir(char * loc){
DIR *d;
struct dirent *dir;
char contenu[10000];
char position[1000];
char modification[20];
char surcontenu[10000];
char souscontenu[10000];
struct stat attrib;
d = opendir(loc);
strcpy(position, loc);
if (d) {
while ((dir = readdir(d)) != NULL) {
strcpy (contenu,dir->d_name);
strcat(position,"\\");
strcat(position,contenu);
stat(position,&attrib);
strftime(modification, 20, "%d-%m-%y", localtime(&(attrib.st_mtime)));
if(S_ISDIR(attrib.st_mode)){
printf("attempt at research \n");
strcpy(souscontenu, regarder_dir(position));
strcat(surcontenu, souscontenu);
}
strcat(position,"\n");
strcat(position,modification);
strcat(position,"\n \n");
strcat(surcontenu,position);
strcpy(position,loc);
modification[0]=0;
}
closedir(d);
}
return(&surcontenu);
}

How do I find instances of a file in directory/sub-directories in C?

So I have a program, and with a passed filename, I need to find/open all files with that name that exist in the current directory and all sub-directories.
I do not know the names of the subdirectories. I do not care about their names or any other files, I just need to be able to open all files with the passed name.
Thanks!
Here's an example with ntfw().
#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf){
char *fileName = "findMe.txt";
/* fpath holds the full path of the file from the specified starting directory */
if ( strstr(fpath, fileName) ){
printf("Match found!\n");
}
return 0;
}
int main(int argc, char **argv){
/* If a starting directory isn't specified, use the current dir */
if (nftw((argc < 2) ? "." : argv[1], display_info, 20, 0) == -1) {
perror("nftw");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}

Segmentation Fault outside the loop only

Using C on Linux, I'm writing a code that stores all the information about the files in a directory using function stat() and prints them on the Terminal
The algorithm is quite simple, I made a structure array of "files" and dynamically allocated them. The structure contains a char array (string) so I dynamically allocated it too.
The thing is .. the dynamic allocation works fine but if I'm inside the while loop I can access the other element inside the structure - which is a structure stat object - but if I access it after the loop finishes, it gives me "Segmentation Fault"!
Here's the code
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <dirent.h>
struct file{
char* name;
struct stat fbuf;
};
int main(int argc, char **argv)
{
char* dir=NULL;
int k;
dir=(char *)malloc(strlen(argv[argc-1])+1);
dir=argv[argc-1];
strcpy(dir,argv[argc-1]);
DIR *curr_dir;
struct dirent *dir_inode;
int i,j=0;
char* sum=NULL;
struct file* files=NULL;
if ((curr_dir = opendir(dir)) == NULL) {
fprintf(stderr, "Can't Open %s\n", argv[1]);
exit(2);
}
while (((dir_inode = readdir(curr_dir))) != NULL) {
files=(struct file*) realloc(files,((j)+1)*(sizeof(char*)+sizeof(struct stat))); // Structure array reallocation
(files+(j))->name=(char *)(malloc(strlen(dir_inode->d_name)+1));//name allocation
for(i=0;i<strlen(dir_inode->d_name);i++)
(files+(j))->name[i]=dir_inode->d_name[i];//name storage
(files+(j))->name[i]='\0';
sum= (char *) malloc(strlen(dir)+strlen(dir_inode->d_name)+2);//To add file name to its directory
for(i=0;i<strlen(dir);i++)
sum[i]=dir[i];
sum[i]='/';
i++;
for(k=0;dir_inode->d_name[k]!='\0';k++)
sum[i+k]=dir_inode->d_name[k];
sum[i+k]='\0';//file name with directory in sum
if( stat(sum,&((files+j)->fbuf)) == -1){ // the function gets information from the file name and stores them in fbuf
printf("error stat\n");
exit(1);
}
free(sum);
if( S_ISDIR( ( (files+(j))->fbuf ).st_mode ) ){
printf("d");
}
else {
printf("-");
}
//Here the output appears fine
//The output depends on accessing fbuf in files array
printf("statOK\n");
(j)++; // index
}
printf("%d %d %d\n",files,j,files+1);
printf("%d\n",j);
printf("\n\n\n\n");
for(i=0;i<j;i++){
printf("%s\n",(files+i)->name);
printf("%d\n",files);
//Starting from here, same syntax but outside the loop it gives the error
if( S_ISDIR( ( (files+i)->fbuf ).st_mode ) ){
printf("d");
else {
printf("-");
}
}
free(files);
free(dir);
closedir(curr_dir);
exit(1);
}
The code isn't complete yet but all what I want is to access the fbuf outside the loop, then I can complete it
Any ideas?
Bad size assumption
This allocation is wrong:
files=(struct file*) realloc(files,((j)+1)*(sizeof(char*)+sizeof(struct stat)));
Here, you assumed that the size of struct file was the sum of the sizes of its two components. But in fact, you don't know how that structure is packed and aligned, so the size of struct file could be larger than what you thought. You should just be using sizeof(struct file) instead:
files=(struct file*) realloc(files,(j+1)*(sizeof(struct file)));

Reading config file in C using libconfig

I defined a structure for options in my config file and a pointer to this structure in "config.h" file and I read config file using libconfig and set values in function get_config() that is defined in file "config.c". In main function I initialize pointer to structure and call get_config() function. libconfig works well and prints values of structure's fields correctly but when I print same fields in main functions their values are incorrect!
"config.h"
#include <stdio.h>
#include <stdlib.h>
#include <libconfig.h>
typedef struct
{
int buffer_size;
const char * DBusername;
const char * DBpassword;
}conf;
conf *config;
int get_config();
"config.c"
#include "config.h"
int get_config()
{
config_t cfg;
config_setting_t *setting;
config_init(&cfg);
/* Read the file. If there is an error, report it and exit. */
if(! config_read_file(&cfg, "config.cfg"))
{
fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
config_error_line(&cfg), config_error_text(&cfg));
config_destroy(&cfg);
return(EXIT_FAILURE);
}
if(config_lookup_int(&cfg, "buffersize", &config->buffer_size))
printf("buffersize: %d\n\n", config->buffer_size);
else
fprintf(stderr, "No 'buffersize' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBusername", &config->DBusername))
printf("DBusername: %s\n\n", config->DBusername);
else
fprintf(stderr, "No 'DBusername' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBpassword", &config->DBpassword))
printf("DBpassword: %s\n\n", config->DBpassword);
else
fprintf(stderr, "No 'DBpassword' setting in configuration file.\n");
config_destroy(&cfg);
return(EXIT_SUCCESS);
}
"store.c"
int main(){
config = (conf*) malloc(sizeof(conf));
if(get_config() == EXIT_FAILURE)
return 0;
printf("\n%s", config->DBusername);
printf("\n%s", config->DBpassword);
printf("\n%d", config->buffer_size);
}
The problem is because of defining char* in structure. I changed the char* to char[] and the problem is solved! :)
I defined a structure for options in my config file and a pointer to this structure in "config.h" file...
That statement makes me wonder what a config file is. i.e. is it a .c, or a .h? And what is the visibility to it for other files?
Your issue is likely because the scope (visibilty) of the structure is not provided to the file in which the main() function resides. #include the .h where the struct is defined, and make sure an instantiation of that struct either has global scope, or create an instantiation inside main()
This configuration of files will provide visibility to to main of a struct defined in the .h:
in somefile.h:
typedef struct
{
int membername;
} A_STRUCT;
extern A_STRUCT a
;
in someotherFile.c
#include "somefile.h"
A_STRUCT a = {3}; //global copy of the struct, with assignment
int main(void)
{
printf("%d", a.membername);
return 0;
}

Using the standard C library or POSIX library to scan for a file in a UNIX directory

Is there anyway for a C program to view the files in a certain directory and interface with them? For example, lets say that I downloaded a file using wget via the system() function, and I want to see what the file's name was. Is there any way for me to accomplish this through only the standard C library or the POSIX library?
This looks for files in a directory that were modified less than 5 seconds ago - there is NO error checking.
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <time.h>
#include <dirent.h>
void dirchk(const char *arg) // arg=name of directory
{
time_t when = time(NULL) -5; // 5 secs ago
struct stat st;
DIR *dirp=opendir(arg);
struct dirent *d=readdir(dirp);
while (d != NULL)
{
if ((d = readdir(dirp)) != NULL)
{
stat(d->d_name, &st);
if( when - st.st_mtime <=5 )
printf("%s\n", d->d_name);
}
}
closedir(dirp);
return;
}
int main()
{
dirchk(".");
return 0;
}
"." is the current working directory.

Resources