mainajaved
mainajaved

Reputation: 8173

open different file using C programming

Hello ever one I want to ask a question about file opening.I want to write a program in which I will give a path to my main folder.main folder can contain files and and other folders which in again contain other folders and files.I want to open all the file in the loop and do some manipulation on them also I want to open only specific file for example .c extended file.Is there a built in program or function that do that? or atleast is there a way through which I can check which files are there in the folder so that I can repeatedly open them

I am using C programming linux Thanks

Upvotes: 0

Views: 726

Answers (3)

Duck
Duck

Reputation: 27552

You can save yourself a lot of work and look at ftw() and nftw(). They will walk through directories and their entries , starting with the path you provide, and a call a callback function that you provide. In your callback you can check if the file is relevant for purpose and operate on it if it is.

Also glob() will save you some effort if you are going to be doing a lot of filename matching.

Upvotes: 2

ugoren
ugoren

Reputation: 16441

opendir, readdir, closedir.
if dirent->d_type==DT_DIR, descend into it (recursion would help).
Take a look at the file name, figure out if you're interested.

Upvotes: 0

c0dehunter
c0dehunter

Reputation: 6150

I am not aware of any built-in functions for what you want to do here. But you could use dirent.h.

int main(){
  DIR *dir;
  struct dirent *ent;
  dir = opendir ("c:\\folder\\");
  if (dir != NULL) {

    /* print all the files and directories within directory */
    while ((ent = readdir (dir)) != NULL) {
      printf ("%s\n", ent->d_name);
    } 
    closedir (dir);
  } else {
    /* could not open directory */
    perror ("");
    return EXIT_FAILURE;
  }
}

Here you can find even more examples.

Upvotes: 1

Related Questions