Showing posts with label C language. Show all posts
Showing posts with label C language. Show all posts

Thursday, March 28, 2013

Getting FILE information Via Stat in C Language

We know that Linux/Unix file system stores information for every file. Some of the information can be obtain by stat - A Unix system call. This system call is defined in < sys/stat.h> header file.

stat structure has the following fields.

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for file system I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};


Now lets write a small program to get the file information using stat system call.

// File name Stat.c

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
    if(argc != 2)   
        return 1;

    struct stat fileInfo;
    // getting file information into fileInfo using stat
    if(stat(argv[1],&fileInfo) < 0)   
        return 1;

    // printing file information
    printf("Information for %s\n",argv[1]);
    printf("---------------------------------------------------\n");
    printf("File Size: \t\t%d bytes\n",fileInfo.st_size);
    printf("Number of Links: \t%d\n",fileInfo.st_nlink);
    printf("File inode: \t\t%d\n",fileInfo.st_ino);

    // S_ISDIR, S_IRUSR,....are marcos
    printf("File Permissions Are: \t");
    printf( (S_ISDIR(fileInfo.st_mode)) ? "d" : "-");
    printf( (fileInfo.st_mode & S_IRUSR) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWUSR) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXUSR) ? "x" : "-");
    printf( (fileInfo.st_mode & S_IRGRP) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWGRP) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXGRP) ? "x" : "-");
    printf( (fileInfo.st_mode & S_IROTH) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWOTH) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXOTH) ? "x" : "-");
    printf("\n");

    return 0;
}


To Run: gcc Stat.c
              ./a.out Stat.c  // giving Stat.c file name as input

Out Put: 
Information for Stat.c
----------------------------------------
File Size:         1256 bytes
Number of Links:     1
File inode:         2367639
File Permissions Are:     -rw-r--r--

Wednesday, February 27, 2013

IPC Using PIPE Mechanism

IPC - Stands for Inter Process Communication

PIPE - There are different mechanisms to achieve IPC, one of them is PIPE. Other IPC mechanisms are Message passing, shared Memory and semaphores. To understand PIPE concept please see the following pic.



Fork()- This function is used to create parent and child process. Fork returns 2 times. 1st time it returns 0 in child process, 2nd time it returns 1 in parent process.

See the following code where child and parent process do IPC using PIPE concept. The child process waits for a key press, and then informs the parent process about it. The parent process waits for this information and then exits.


/* program to demonstrate usage of pipes */

#include <stdio.h>
// unistd.h is needed in C++ compilers
#ifdef __cplusplus
#include <unistd.h>
#endif

void main()
{

 int pfd[2]; // pfd - Pipe File Descriptor

 if(pipe(pfd) < 0)
    printf("\n Pipe error");

if(!fork())
{
   //child process
   char reni;
   printf("\n Enter any character to Exit:");
   scanf("%c", &reni);
   // writing to pipe
   write(pfd[1], &reni, 1);
   //child exit
  printf("\n Child Exiting..!");
  exit(0);
}
else
{
  // parent process
  char sam;
  // reading from pipe
  read(pfd[0], &sam, 1);
  printf("\n Parent Received %c from Child", sam);
  printf("\n Parent Exiting..!");
  exit(0);
}

}

Sunday, February 24, 2013

Curious Q's of C-Langunage

NOTE: These all are tested/executed on  GCC compiler


Q-34-----------------------------
This program will run or not?
#include <stdio.h>
int (SQUARE)(int x)
{
return x*x;
}
void main()
{
printf("square of 5 is %d", SQUARE(5));
}
A-34
Yes it will run. It will print
square of 5 is 25



Q-33-----------------------------
Write a simple C program to print your name on console without using semi-colon, if, for, switch, while, do-while, char, int, float?
A-33
#include <stdio.h>
#define PRINT printf("I am Bramha")
#define FUNC S[PRINT]
void main(void* FUNC) {}



Q-32-----------------------------
What is the output of following code snippet?
#include <stdio.h>
void main()
{
int array[5]= {[2]=25};
int i=0;
for(i=0;i < 5 ; i++)
printf("%d ", array[i]);
}
A-32
0 0 25 0 0
if we intialize array like this, defaultly it initializes all others to 0.




Q-31-----------------------------
In GCC sizeof(AnyFunct­ionName) or sizeof(void)?
A-31
1 byte


Q-30-----------------------------
write a C code to find whether given number is power of 2 or not?
A-30
#include <stdio.h>
void main()
{
   int reni;
   scanf("%d", &reni);
   if(reni & (reni-1)) // Binary AND
     printf("\n Not power of 2");
   else
     printf("\n power of 2");
}


Q-29-----------------------------
What is the output of following code snippet?
#include <stdio.h>
void main()
{
   int reni;
   for(reni=0;reni < 5 ; reni++)   {
       printf("%d ", reni??!??!reni);
   }
}
A-29
It is using trigraphs. to run this use 'gcc filename.c - trigraphs'
in trigraphs ??!??! == ||
so out put is 0 1 1 1 1



Q-28-----------------------------
What is the output of following code snippet?
#include <stdio.h>
void main(void)
{
  int r, s;
  for (r = 0; r < 5; r++)
  {
       s = r &&& r;
       printf("%d ", s);
  }
}
A-28
0 1 1 1 1 ( 'r &&& r' is equal to 'r && (&r)' )



Q-27-----------------------------
What is the output of following code snippet?
#include<stdio.h>
void main() {
    int reni = 777;
    sizeof(reni++);
    printf("%d\n", reni);
}
A-27
777 (sizeof is compile time operator so it's operand is replaced by value)



Q-26-----------------------------
Why a[7]=7[a] in C? where 'a' is array
A-26
Becoz array access is defined in terms of pointers. a[7] will become *(a+7) which is commutative



Q-25-----------------------------
difference between gets and fgets functions?
A-25
gets won't do array bound checking which causes buffer overflow. fgets do array bound checking.



Q-24-----------------------------
Write a program to add 2 non-zero positive integers without using any operator?
A-24
#include <stdio.h>
void main()
{
 int a, b;
 scanf("%d%d",&a, &b);
 printf("\n saum is =%d", printf("%*c%*c", a, '\r', b, '\r'));
}



Q-23-----------------------------
what is the output of following code snippet?
#include <stdio.h>
void main()
{
   char arr[] = "reni"; // terminated with '\0'
   char arr1[4] = "reni"; // not terminated with '\0'
   char arr2[] = { 'r', 'e', 'n', 'i'}; \\ not terminated with '\0'
   printf("%d %d %d", sizeof(arr),sizeof(arr1), sizeof(arr2) );
}
A-23
5 4 4



Q-22-----------------------------
what is the output of following code snippet?
#include <stdio.h>
int main()
{
  int a, b;
  ++a = 10;
  b++ = 20;
  printf("\n a=%d, b=%d", a, b);
  return 0;
}
A-22
Compilation error. In C Pre and post-increments can't be used as l-value. In C++ only post-increment can't be used as l-value.



Q-21-----------------------------
what is the output of following code snippet?
#include <stdio.h>
int main()
{
  int j=7;
  printf("j = %d", ++(-j));
  return 0;
}
21-A
gives compilation error, Becoz -j returns r-value where we need l-value to store that. In other way -(++j) works fine.



Q-20-----------------------------
What is the output of following code(coma operator)?
#include <stdio.h>
int main()
{
  int i, j;
  (i, j) = 30;
  printf("j = %d", j);
  return 0;
}
A-20
compilation error. Becoz result of coma operator can not use as l-value in C but in C++(g++) it will work.



Q-19-----------------------------
What is the output of following code(coma operator)?
#include <stdio.h>
void main()
{
    int var= 1, 3, 7;
    printf("%d", var);
}
A-19
Compilation error



Q-18-----------------------------
What is the output of following code(coma operator)?
#include <stdio.h>
void main()
{
    int var;
    var = 1, 3, 7;
    printf("%d", var);
}
A-18
1



Q-17-----------------------------
What is the output of following code(coma operator)?
#include <stdio.h>
void main()
{
    int var;
    var = (1, 3, 7);
    printf("%d", var);
}
A-17
7



Q-16-----------------------------
What is the output of following code?
#include <stdio.h>
void main()
{
  int val;
  printf("Reni%nSam", &val);
  printf("\n%d", val);
}
A-16
ReniSam
4 (number of characters before %n will load into 'val' variable)



Q-15-----------------------------
Following code snippet will work or not?
#include <stdio.h>
int staticValue()
{
    return 50;
}
void main()
{
    static int sam = staticValue();
    printf("\n Value of sam =%d", sam);
}
A-15
It flashes "initializer element is not constant" error. Becoz static variables intialize before main execution and staticValue function called after main only.



Q-14-----------------------------
what is the difference between following 2 statements?
extern int sam;
int reni;
A-14
1st one is a declaration
2nd one is definition



Q-13-----------------------------
Explain volatile qualifier in C?
A-13
Volatile variable is omitted from compiler optimization because their values can be changed by code outside the scope of current code at any time. For example Global variables modified by an interrupt service routine outside the scope.



Q-12---------------------------------------
what is the output of following code snippet?
#include <stdio.h>
void main()
{
  printf("\n%d", func());
}
int func()
{
  printf("\nRen");
}
A-12
Ren
4
Here 4 is the size of string with including '\0', which is a string terminator.



Q-11---------------------------------------
following declarations will work or not?
short i;
static j;
unsigned k;
const l;
volatile m;
A-11
Yes, All above declarations will work becoz default  datatype of all above declarations are Integer.



Q-10-----------------------------------------------
How global and local static variables with same name are differentiate in data-segment?
#include <stdio.h>
static int IntSam;
 void main()
{
   static int IntSam;
}  
10-A
local static int IntSam is appended with '.' and some integer number to differentiate from global static int IntSam. To check this, run above code snippet. Open generated object file in VI editor and look for IntSam in that.



Q-9------------------------------------------------
How to find the size of any datatype without using sizeof operator?

A-9
#include <stdio.h>
void main()
{
   int *intptr =0;
   float *floatptr =0;
   char *charptr=0;
   // union student *stdUnion = 0;
   // struct student *stdStruct = 0;
   intptr++;
   floatptr++;
   charptr++;
   //stdUnion++;
   // stdStruct++;
    printf("\n size of integer = %d", intptr);
    printf("\n size of Float = %d", floatptr);
    printf("\n size of char = %d", charptr);
   // printf("\n size of Union = %d", stdUnion);
   // printf("\n size of Struct = %d", stdStruct);
}
 


Q-8------------------------------------------------
Write 2 functions in such a way that one function will called before main function and another will called after main function.
A-8
#include <stdio.h>
void beforeMain(void) __attribute__((constructor));
void afterMain(void) __attribute__((destructor));
void main()
{
   printf("\n In Main");
}
 void beforeMain(void)
{
  printf("\n Before Main");
}
void afterMain(void)
{
  printf("\n After Main");
}



Q-7------------------------------------------------

Following code snippet will work? If yes what is the output?
#include <stdio.h>
int main()
{
  printf("\n%.*d", 4, 7);
  return 0;
}
A-7
Yes above code snippet will work. In above printf '*' is replaced by 4 and %.*d will become %.4d. Out put is 0007.



Q-6------------------------------------------------
What is the output of following code snippet?

#include <stdio.h>
struct num{
int sam:3;
};
int main(){
struct num n={-6};
printf("%d",n.sam);
return 0;
}

A-6
Binary value of 6: 00000110
Binary value of -6: 11111001+1=11111010
Select last 3 bits only becoz only 3 bits allocated = 010 = 2
Output is: 2



Q-5------------------------------------------------
What is  short-circuiting in C expressions?
A-5
In C expression the right hand side of the expression is not evaluated if the left hand side determines the outcome and vice verse. For example the left hand side is true for || or false for &&, the right hand side is not evaluated.



Q-4------------------------------------------------
following code will work or not?

#include <stdio.h>
void main()
{
  int a;
  printf("%d\n", sizeof a);
}

A-4
Yes, it will work becoz, sizeof is a operator not a function.



Q-3------------------------------------------------
 Write C function to decide whether given machine is big or little Endian 
A-3
#include <stdio.h>
void main()
{
union {
int reni;
char sam[sizeof(int)];
} endian;

endian.reni = 1;
if(endian.sam[0] == 1)
printf("\n Your machine is Little_endian");
else
printf("\n Your machine is Big_endian");





Q-2------------------------------------------------
What the following function will do?

#include <stdio.h>
void main()
{
     write(1,"\33[H\33[2J", 7);
}
A-2 it clears console and moves cursor to home in command prompt.




Q-1------------------------------------------------
What is the data type of Var, Var1 in the following function

void main()
{
     __typeof(1.0) var;
     __typeof(1.0) var1;
}
A-1
Var- Integer
Var1- Float