Scan all files in Linux using C [duplicate] - c

This question already has answers here:
stat() error 'No such file or directory' when file name is returned by readdir()
(2 answers)
Closed 5 years ago.
I am trying to scan all files in my computer, including files in subdirectories. The program should start in the root folder "/".
logfind.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <stdlib.h>:
#include <dirent.h>
int is_directory(const char *path) {
struct stat path_stat;
stat(path, &path_stat);
return S_ISDIR(path_stat.st_mode);
}
void list_files(char *pathus) {
struct dirent *de;
DIR *dr = opendir(pathus);
if (dr == NULL) {
printf("Could not open current directory");
exit(1);
}
while ((de = readdir(dr)) != NULL) {
if (is_directory(de->d_name) > 0)
list_files(de->d_name);
else
printf("%s\n", de->d_name);
}
closedir(dr);
}
int main(int argc, char **argv) {
list_files("/");
return 0;
}
The output I get when running this is basically "logfind.c" many times,
anyone has an idea as to why this happens?

This happens because there's nothing in your code to change the process' current directory, or build the full path of the directory to scan.
If you're in /home/danny/src/ when you run this, and find dev while listing /, you can't opendir("dev"), that'd mean /home/danny/src/dev, not /dev.

Related

Get files access permissions using stat() in C

I just started learning linux/C, i just want to show the names of all the files of the directories given in argument, and their access permissions by using stat() which causes some problems.
It actually shows the correct name/mode of all the files included in the current directory, but for the other directories given in argument, it does give the right name but the same st_mode for all the files...
here's my code:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
printf("Hello, world!\n");
int status;
struct stat sbuf;
DIR *dirp;
struct dirent *dp;
dp = (struct dirent*) malloc(sizeof(struct dirent));
for (int i=1; i<argc; i++){
dirp = opendir(argv[i]);
if (dirp == NULL){/*perror("Argument invalide");*/printf("Argument %d invalid", i); exit(1);}
printf("\n\nOpening %s\n", argv[i]);
do{
dp = readdir(dirp);
if (dp != NULL && strcmp(dp->d_name,".") && strcmp(dp->d_name, "..")) {
status = stat(dp->d_name,&sbuf);
printf("The file is %s \tMode :%o\n", dp->d_name, (sbuf.st_mode & 0777));
}
} while (dp != NULL);
closedir(dirp);
}
return 0;
}
for example I did try this :
gcc -o test main.c then
./test . ..
And here's the result !
Opening .
The file is c.txt Mode :644
The file is d.txt Mode :644
The file is xxxx.txt Mode :777
The file is test Mode :755
Opening ..
The file is a.txt Mode :755
The file is b.txt Mode :755
The file is dossier Mode :755
The file is main Mode :755
The file is main.c Mode :755
The file is test Mode :755
As you can see, all the files of the " .. " directory have the same Mode, which is completely wrong... I did try with full paths and different directories, same problem.
Well, stat isn't giving you the file information because readdir gives you the file name, not the path. Try something like this to build up the path so you can actually call stat.
char *path = malloc(strlen(dp->d_name) + strlen(argv[i]) + 2);
stpcpy(stpcpy(stpcpy(path, argv[i]), "/"), dp->d_name);
status = stat(path,&sbuf);
free(path);

Undefined Reference to 'main' when code is compiled

I created a C program which would create a directory and file.
I have tried to debug the error, but it didn't work
#include <dirent.h>
#include <errno.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
create_dir(char* outputdir,char* str_outpath,char* value){
DIR* dir = opendir(outputdir);
FILE *f;
if (dir) {
/* Directory exists. */
closedir(dir);
} else if (ENOENT == errno) {
/* Directory does not exist. */
mkdir(outputdir, 0700);
closedir(dir);
printf("Successfully created the directory %s ", outputdir);
} else {
printf("Creation of the directory %s failed",outputdir);
/* opendir() failed for some other reason. */
}
f = fopen(str_outpath, "a");
fprintf(f,"%s",value);
fclose(f);
}
I want it to create a file and a directory successfully
As others have mentioned. You do not have a main function.
Also your create_dir function is missing a type. I'll assume it's void since you are not returning anything. This should compile.
#include <dirent.h>
#include <errno.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
void create_dir(char* outputdir,char* str_outpath,char* value){
DIR* dir = opendir(outputdir);
FILE *f;
if (dir) {
/* Directory exists. */
closedir(dir);
} else if (ENOENT == errno) {
/* Directory does not exist. */
mkdir(outputdir, 0700);
closedir(dir);
printf("Successfully created the directory %s ", outputdir);
} else {
printf("Creation of the directory %s failed",outputdir);
/* opendir() failed for some other reason. */
}
f = fopen(str_outpath, "a");
fprintf(f,"%s",value);
fclose(f);
}
int main(){
char directory[] = "/users/me/documents/testdir";
char filepath[] = "testfile";
char data[] = "hello world";
create_dir(directory,filepath,data);
return 0;
}
I did not execute the code to check whether it works. I merely copied and pasted yours and called the function.
In C under most cases you need to have a main function. So in order to run your code you'll need to have something like this (assuming that you want to pass in the parameters from the command-line) underneath that function:
int main(int argc, char *argv[]) {
if (argc < 4) {
printf("Proper Usage is ./program otputdir str_outpath value\n");
return -1;
}
char *outputdir = argv[1];
char *str_outpath = argv[2];
char *value = argv[3];
create_dir(outputdir, str_outpath, value);
return 0;
}
EDIT: fixed an issue with not checking argc

How to move the files from one directory to another in c?

I am creating a project on moving a directory files by creating sub-folders according to their particular type in c. I have made up to creating directories with the help of POSIX library dirent.h for the files having different extension present in the home directory but I don't know how to cut a file from home directory and paste in its particular sub-folder. So please guide me about how can I cut and paste a file from one directory to another in c.
Use rename(DestinationFilepath, SourceFilepath);
For more info check man page http://linux.die.net/man/2/rename
For two different system use cURL library:
http://en.wikipedia.org/wiki/CURL
Code in C:
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <time.h>
#define DESTINATION_FOLDER "/home/second/"
#define SOURCE_FOLDER "/home/first/"
void printdir()
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
struct tm *tm;
char src_folder[1024];
char dest_folder[1024];
if ((dp = opendir(SOURCE_FOLDER)) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", SOURCE_FOLDER);
return;
}
chdir(SOURCE_FOLDER);
while ((entry = readdir(dp)) != NULL) {
lstat(entry->d_name, &statbuf);
if (!S_ISDIR(statbuf.st_mode)) {
sprintf(src_folder, "%s%s", SOURCE_FOLDER, entry->d_name);
sprintf(dest_folder, "%s%s", DESTINATION_FOLDER, entry->d_name);
printf("%s----------------%s\n", entry->d_name, dest_folder);
rename(src_folder, dest_folder);
}
}
chdir("..");
closedir(dp);
}
int main()
{
while (1) {
printdir();
}
rename("aaa.txt", "/home/second/bbb.txt");
printf("done.\n");
exit(0);
}

C Directory and Subdirectory Recursion

I tried to recursively get all files and folder list.But I can only get subdirectories of documents and inside of them.I can't get the other folders which in inside of subdirectory.
I don't know how to do it recursively.I hope you help me
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <windows.h>
#include <unistd.h>
#include <string.h>
void list(char *a);
void reader(char *path);
int
main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("C:\\Users\\pen\\Documents\\");
if (dp != NULL)
{
while (ep = readdir (dp)){
GetFileAttributes(ep->d_name);
if(FILE_ATTRIBUTE_DIRECTORY & GetFileAttributes(ep->d_name))
{
if (strcmp(".",ep->d_name)==0)
continue;
if (strcmp("..",ep->d_name)==0)
continue;
reader(ep->d_name);
}
}
closedir(dp);
}
else
perror ("Couldn't open the directory");
closedir(dp);
system("pause");
return 0;
}
void reader(char *path){
DIR *da;
struct dirent *ef;
da = opendir(path);
while (ef=readdir(da)){
printf ("%s\n",ef->d_name);
if(FILE_ATTRIBUTE_DIRECTORY & GetFileAttributes(ef->d_name))
{
if (strcmp(".",ef->d_name)==0)
continue;
if (strcmp("..",ef->d_name)==0)
continue;
reader(ef->d_name);
}
}
closedir(da);
}
1) In reader you need to call closedir(da); after the while loop.
2) every call to reader needs to have the absolute path you need to concatenate path
to ef->d_name and then call reader.
3) also to enable debugging you should call perror after a failed readdir call.

EXT2 Directory Content

Hi I reached inode 2 , the root directory. I know the direct block number of it, which is 265. How can I list the content of the root directory in C?
This should work. I suggest looking up the man pages for opendir() and readdir(). This is not based on inodes. Do you require to be able to look up directories based on inode?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
int main() {
DIR *dir = opendir("/");
if(dir==NULL) {
perror("Couldn't open dir");
exit(1);
}
printf("opened\n");
struct dirent * entry;
while((entry = readdir(dir))) {
printf("%s\n", entry->d_name);
}
return 0;
}

Resources