1

Got a doubt about file system manipulation: opening a file in a different directory where we execute our program.

Lets say we execute our program in the following directory: /home/example and we want the program to go to another directory, say: home/example/Inside/Test and open all the txt files in this last directory.

Ok so a small code:

  /*variables*/
  struct dirent *strdir;
  DIR *diro; 
  struct stat statbuffer;
  char *path = /home/example/Inside/test

  diro = opendir( path )
  /*cheked it opened properly*/
  while ( (strdir = readdir(diro)) != NULL ){
     stat(strdir->d_name, &statbuffer);         /*Gets information of file*/
     if (S_ISREG(statbuffer.st_mode)){
       /*its regular type*/
       /*check its of type txt*/
       ???

I put ??? because I used fopen, and it doesn't work. Of course it doesn't, because that file does not exist in /home/example. Same goes for open.

So I thougth, maybe I can concatenate the directory and the file name into a single char to get the full path, but that sounds kind of ugly...

The other idea is to use the information given to me by stat, but I can't seem to figure out how to make it work. Hard links?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Alessandroempire
  • 1,640
  • 4
  • 31
  • 54
  • 2
    Post your real code, please, and not something you made up or changed first. If you have to change things for security reasons, change the minimum necessary. Posting fake code is like going to your car repair shop and saying "What's wrong with my car? I didn't bring it, but it looks kind of like the one parked over there, and the funny sound it's making is sort of like the one from that car that just drove by." – Ken White Jun 15 '12 at 01:35

2 Answers2

0

It seems whatever parameter you specify to this function needs to be a string.

    opendir( /home/example/Inside/Test )

See this SO question Open directory using C

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
0

If you don't want to put the directory name on your paths (which is probably the right thing to do), call chdir("/home/example/Inside/Test");

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441