Showing posts with label opendir. Show all posts
Showing posts with label opendir. Show all posts

Unix System Calls - open, read, write, close, exit



// Unix system calls
// open, read, write, close system calls

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h> 
#include <fcntl.h>    

int main (int argc, char *argv[])
{
        int fd;
        int n_char=0;
              char buffer[10];

        fd=open(argv[1],O_RDONLY);
        if (fd==-1)
        {
                   printf("File open error.");
                   exit(1);
        }

       
        while( (n_char=read(fd, buffer, 1))!=0)
                   n_char=write(1,buffer,n_char);
       
        close(fd)
        return 0;
}

Unix System Calls - opendir readdir


// Unix system calls
// opendir, readdir

#include <stdio.h>
#include <dirent.h>

int main()
{
          struct dirent *de; 

          DIR *dr = opendir(".");

          if (dr == NULL)
          {
                   printf("Could not open current directory" );
                   return 0;
          }

          while ((de = readdir(dr)) != NULL)
                             printf("%s\n", de->d_name);

          closedir(dr);
          return 1;


}

Unix System Calls - stat


Unix System Calls

// Unix system calls
// stat

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

void main(int argc, char **argv)
{
    if(argc != 2)   
        printf("Usage error: Invalid number of arguments.");

    struct stat fs;
    if(stat(argv[1],&fs) < 0)   
        printf("Usage error: File / directory does not exist.");

    printf("Information for %s\n",argv[1]);
    printf("File Size: \t\t%d bytes\n",fs.st_size);
    printf("File inode: \t\t%d\n",fs.st_ino);
    printf("File mode: \t\t%d\n",fs.st_mode);
    printf("user ID of file owner: \t%d\n",fs.st_uid);
    printf("File last access time: \t%d\n",fs.st_atime);
    
}