How to access directory files in C? - c

I'm trying to add all the files in the current directory to my implemented archive. What function(s) could I use to access all these files? After doing some research online and in the man pages, all I have found is simple I/O like read, write, close, etc.

You can try with this.
main() {
DIR *d;
struct dirent *e;
e=malloc(sizeof(struct dirent));
d=opendir("<your_directory_name>");
while ((e = readdir(d)) != NULL) {
printf("%d %s\n", e->d_type, e->d_name);
}
closedir(d);
}

In Unix, readdir ; in Windows, see here for FindFirstFile(). Then go file by file in a loop and do what you want.

This web page seems to have what you want.
http://www.gnu.org/software/libc/manual/html_mono/libc.html#Opening-a-Directory

Related

C language parse file's detail

I'm a beginner with C.
I want to parse all the source code (e.g., *.c, *.h) under a directory.
I want to know the file name, size, how many lines in the source.
After searching, I can parse one file's detail (to get how many lines in the source). I can also use system() to know the size and file name, or file list in the directory (without size).
But I have no idea about how to combine all these into one program, so I'm looking for guidance on that.
Thanks all!
below is my code for now
have no idea about next step..
int main (void){
DIR *dp;
FILE *fp;
struct dirent *ep;
dp = opendir ("./");
fp = fopen ("output.txt", "w");
if (dp != NULL)
{
while (ep = readdir (dp))
fprintf(fp,"%s\n", ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
Here's the things you need to look in to:
how to iterate over file names, such as with opendir(), readdir() and so on, including while statement for the actual iteration of course.
how to get file details, such as with fstat().
how to open and read files, such as with fopen(), fgetchar() and fclose(), including how to recognise line end characters with if.
That should be the tools you need to start the job, I'd suggest looking in to them then trying to construct your program. Specific problems with the program can then be bought to our attention in other questions.
Note that the examples given above (specifically those in the opendir bullet point) may be platform-specific. If they're not available, you'll need to find equivalents for your platform since standard C does not provide that functionality.

how to access particular file in folder through file handling in c

I have suppose two text file abc.txt and def.txt in folder "my". I have a programme which directly goes to that folder and search particular file and if that particular file find out then how to access that file's information.
I know how to read write file in C through file handling but I have no idea how to search particular file and after that read that particular file to match particular string in file.
**All these things access through file handling in C.**
So please if any one have any solution I will be thankful for that
Example will be best way to understand .
Thanks in advance
To get a listing of the files in a directory in Linux, you can use the 'opendir', 'readdir' and 'closedir' functions from 'dirent.h'. For example:
#include <dirent.h>
#include <stdio.h>
int ListDir(const char *pDirName)
{
DIR *pDir;
struct dirent *pEntry;
pDir = opendir(pDirName);
if (!pDir)
{
perror("opendir");
return -1;
}
while ((pEntry = readdir(pDir)) != NULL)
{
printf("%s\n", pEntry->d_name);
}
closedir(pDir);
return 0;
}

listing the files in a directory and delete them in C/C++

In a "C" code I would like to list all the files in a directory and delete the oldest one. How do I do that?
Can I use popen for that or we have any other solutions??
Thanks,
From the tag, I assume that you want to do this in a POSIX compliant system. In this case a code snippet for listing files in a folder would look like this:
#include <dirent.h>
#include <sys/types.h>
#include <stdio.h>
DIR* dp;
struct dirent* ep;
char* path = "/home/mydir";
dp = opendir(path);
if (dp != NULL)
{
printf("Dir content:\n");
while(ep = readdir(dp))
{
printf("%s\n", ep->d_name);
}
}
closedir(dp);
To check file creation or modification time, use stat (man 2 stat). For removing file, just use function remove(const char* path)
On Linux (and indeed, any POSIX system), you read a directory by calling opendir() / readdir() / closedir(). You can then call stat() on each directory entry to determine if it's a file, and what its access / modification / status-change times are.
If your definition of "oldest" depends on the creation time of the file, then you're on shaky ground - traditionally UNIX didn't record the creation time. On Linux, some recent filesystems do provide it through the extended attribute file.crtime (which you access using getxattr() from sys/xattr.h), but you'll have to handle the common case where that attribute doesn't exist.
You can scan the directory using readdir and opendir
or, if you want to traverse (recursively) a file hierarchy fts or nftw. Don't forget to ignore the entries for the current directory "." and the parent ".." one. You probably want to use the stat syscall too.

Need To Eliminate Directories From File Listing in C

I have a problem, in that I need to get a list of the files in a Directory. Using this previous StackOverflow question as a base, I've currently got this code:
void get_files(int maxfiles) {
int count = 0;
DIR *dir;
struct dirent *ent;
dir = opendir(DIRECTORY);
if (dir != NULL) {
/* get all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
if (count++ > maxfiles) break;
printf("%s\n", ent->d_name);
}
closedir(dir);
} else {
/* could not open directory */
printf("ERROR: Could not open directory");
exit(EXIT_FAILURE);
}
}
Now it works almost exactly how I want it too, but the problem is that its also listing directories in with he files, and I only want file entries. Is there a easy modification I can make to do this?
You can filter directories using code similar to
this one
POSIX defines fstat which can be used for the purpose of checking whether a file is a directory. It also has a macro to simplify the check.
http://linux.die.net/man/2/fstat
Note that for Windows you may have to use windows API here.
If your struct dirent contains the nonstandard-but-widely-available d_type member, you can use this to filter out directories. Worth having an option to use it and only falling back to stat on systems that don't, since using d_type rather than stat will possibly make your directory listing tens or hundreds of times faster.

Recursive file delete in C on Linux

I have a C program that, at one point in the program has this:
system("rm -rf foo");
Where foo is a directory. I decided that, rather than calling system, it would be better to do the recursive delete right in the code. I assumed a piece of code to do this would be easy to find. Silly me. Anyway, I ended up writing this:
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h>
#include <libgen.h>
int recursiveDelete(char* dirname) {
DIR *dp;
struct dirent *ep;
char abs_filename[FILENAME_MAX];
dp = opendir (dirname);
if (dp != NULL)
{
while (ep = readdir (dp)) {
struct stat stFileInfo;
snprintf(abs_filename, FILENAME_MAX, "%s/%s", dirname, ep->d_name);
if (lstat(abs_filename, &stFileInfo) < 0)
perror ( abs_filename );
if(S_ISDIR(stFileInfo.st_mode)) {
if(strcmp(ep->d_name, ".") &&
strcmp(ep->d_name, "..")) {
printf("%s directory\n",abs_filename);
recursiveDelete(abs_filename);
}
} else {
printf("%s file\n",abs_filename);
remove(abs_filename);
}
}
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
remove(dirname);
return 0;
}
This seems to work, but I'm too scared to actually use it in production. I'm sure I've done something wrong. Does anyone know of a C library to do recursive delete I've missed, or can someone point out any mistakes I've made?
Thanks.
POSIX has a function called ftw(3) (file tree walk) that
walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree.
kudos for being scared to death, that's a healthy attitude to have in a case like this.
I have no library to suggest in which case you have two options:
1) 'run' this code exhaustively
a) not on a machine; on paper, with pencil. take an existing directory tree, list all the elements and run the program through each step, verify that it works
b) compile the code but replace all of the deletion calls with a line that does a printf - verify that it does what it should do
c) re-insert the deletion calls and run
2) use your original method (call system())
I would suggest one additional precaution that you can take.
Almost always when you delete multiple files and/or directories it would be a good idea to chroot() into the dir before executing anything that can destroy your data outside this directory.
I think you will need to call closedir() before recursiveDelete() (because you don't want/need all the directories open as you step into them. Also closedir() before calling remove() because remove() will probably give an error on the open directory. You should step through this once carefully to make sure that readdir() does not pickup the '..'. Also be wary of linked directories, you probably wouldn't want to recurse into directories that are
symbolic or hard links.

Resources