简体   繁体   中英

C open a file for reading in a diferrent directory

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?

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

如果您不想将目录名放在路径上(这可能是正确的选择),请调用chdir("/home/example/Inside/Test");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM