FAQ > Working with files and directories


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > Linux/Unix Specific > Working with files and directories

This item was added on: 2003/03/07

  • How do I determine the current working directory?

  • How do I change the current working directory?

  • How do I obtain file information, like size, creation date, etc?

  • How do I create and remove a directory?

  • How do I read all filenames from a directory?


  • How do I determine the current working directory?

    
    #include <sys/param.h> 
    #include <unistd.h> 
    #include <stdio.h> 
    
    int main(void)
    {
      char buf[MAXPATHLEN];
      if( getcwd( buf, MAXPATHLEN ) ) 
      {
        printf( "%s\n", buf );
      }
      return 0;
    }
    
    



    How do I change the current working directory?
    
    #include <unistd.h> 
    
    if( chdir( "/new/cwd" ) != 0 ) 
    {
      /* chdir( ) error */
    }
    
    



    How do I obtain file information, like size, creation date, etc?

    Use stat( ), or use lstat() for symbolic links and fstat() for open file descriptors.

    int stat(const char *file_name, struct stat *buf);
    int fstat(int filedes, struct stat *buf);
    int lstat(const char *file_name, struct stat *buf);


    
    #include <sys/types.h> 
    #include <sys/stat.h> 
    #include <stdio.h> 
    
    struct stat sb;
    if (stat("filename", &sb) == 0)
    {
      printf("Size: %d\n", sb.st_size);
      printf("Last access: %s\n", ctime(&sb.st_atime));
    
      /* ... */
    }
    
    

    The st_mode member contains information about the file type and access permissions.

    
    #include <sys/types.h> 
    #include <sys/stat.h> 
    #include <stdio.h> 
    
    struct stat s;
    int         i;
    int         modes[] = {
      S_IRUSR, S_IWUSR, S_IXUSR, 
      S_IRGRP, S_IWGRP, S_IXGRP, 
      S_IROTH, S_IWOTH, S_IXOTH 
    };
    
    if (stat("filename", &s) == 0)
    {
      for (i = 0; i < 9; ++i)
      {
        if (modes[i] & s.st_mode)
        {
          putchar("rwx"[i % 3]);
        }
        else
        {
          putchar('-');
        }
      }
    }
    
    



    How do I create and remove a directory?

    
    #include <sys/types.h> 
    #include <sys/stat.h> 
    
    if (mkdir("foo", S_IRWXU) != 0)
    {
      /* mkdir( ) error */
    }
    
    if (rmdir("foo") != 0)
    {
      /* rmdir( ) error */
    }
    
    



    How do I read all filenames from a directory?

    
    #include <dirent.h> 
    #include <stdio.h> 
    
    DIR           *d;
    struct dirent *dir;
    d = opendir(".");
    
    if (d)
    {
      while ((dir = readdir(d)))
      {
        printf("%s\n", dir->d_name);
      }
      closedir(d);
    }
    
    


    Credit vVv

    Script provided by SmartCGIs