Showing posts with label c++. Show all posts
Showing posts with label c++. Show all posts

Saturday, January 28, 2012

Some inportant question of file handeling in c program


Q1). What are the two forms of #include directive?
Ans:
1.#include”filename”
2.#include <>
the first form is used to search the directory that contains the source file. If the search fails in the home directory it searches the implementation defined locations. In the second form ,the preprocessor searches the file only in the implementation defined locations.


Q2). How would you use the functions fseek(), freed(), fwrite() and ftell()?
Ans:
fseek(f,1,i) Move the pointer for file f a distance 1 byte from location i.
fread(s,i1,i2,f) Enter i2 data items, each of size i1 bytes, from file f to string s.
fwrite(s,i1,i2,f) send i2 data items, each of size i1 bytes from string s to file f.
ftell(f) Return the current pointer position within file f.
The data type returned for functions fread, fseek and fwrite is int and ftell is long int.

Q3). What is a file?
Ans: A file is a region of storage in hard disks or in auxiliary storage devices. It contains bytes of
information .It is not a data type.

Q4.) IMP>what are the types of file?
Ans: Files are of two types
1-high level files (stream oriented files) :These files are accessed using library functions
2-low level files(system oriented files) :These files are accessed using system calls

Q5). IMP>what is a stream?
Ans: A stream is a source of data or destination of data that may be associated with a disk or other
I/O device. The source stream provides data to a program and it is known as input stream. The destination stream receives the output from the program and is known as output stream.

Q6). What is meant by file opening?
Ans: The action of connecting a program to a file is called opening of a file. This requires creating
an I/O stream before reading or writing the data.

Q7). What is FILE?
Ans: FILE is a predefined data type. It is defined in stdio.h file.

Q8) What is a stream?
A stream is a continuous series of bytes that flow into or out of your program. Input and output from devices such as the mouse, keyboard, disk, screen, modem, and printer are all handled with streams. In C, all streams appear as files - not physical disk files necessarily, but rather logical files that refer to an input/output source. The C language provides five "standard" streams that are always available to your program. These streams do not have to be opened or closed. These are the five standard streams:
Name

Description

Example
stdin
-
Standard Input
-
Keyboard
stdout
-
Standard Output
-
Screen
stderr
-
Standard Error
-
Screen
stdprn
-
Standard Printer
-
LPT1: port
stdaux
-
Standard Auxiliary
-
COM1: port
Note that the stdprn and stdaux streams are not always defined. This is because LPT1: and COM1: have no meaning under certain operating systems. However, stdin, stdout, and stderr are always defined. Also, note that the stdin stream does not have to come from the keyboard; it can come from a disk file or some other device through what is called redirection. In the same manner, the stdout stream does not have to appear on-screen; it too can be redirected to a disk file or some other device. See the next FAQ for an explanation of redirection.

 Q9) 3. How do you redirect a standard stream?

Most operating systems, including DOS, provide a means to redirect program input and output to and from different devices. This means that rather than your program output (stdout) going to the screen, it can be redirected to a file or printer port. Similarly, your program's input (stdin) can come from a file rather than the keyboard. In DOS, this task is accomplished using the redirection characters, < and >. For example, if you wanted a program named PRINTIT.EXE to receive its input (stdin) from a file named STRINGS.TXT, you would enter the following command at the DOS prompt:
C:>PRINTIT < STRINGS.TXT
Notice that the name of the executable file always comes first. The less-than sign (<) tells DOS to take the strings contained in STRINGS.TXT and use them as input for the PRINTIT program.
Redirection of standard streams does not always have to occur at the operating system. You can redirect a standard stream from within your program by using the standard C library function named freopen(). For example, if you wanted to redirect the stdout standard stream within your program to a file named OUTPUT.TXT, you would implement the freopen() function as shown here:

freopen("output.txt", "w", stdout);

Now, every output statement (printf(), puts(), putch(), and so on) in your program will appear in the file OUTPUT.TXT.

Q10) What is the difference between text and binary modes?
Streams can be classified into two types: text streams and binary streams. Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline n character and vice versa. Binary streams are uninterrupted and are treated one byte at a time with no translation of characters. Typically, a text stream would be used for reading and writing standard text files, printing output to the screen or printer, or receiving input from the keyboard.

A binary text stream would typically be used for reading and writing binary files such as graphics or word processing documents, reading mouse input, or reading and writing to the modem.

File handeling in c program


What is File in c program
 
A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characetrs, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. File handeling in any programming language is necessary to save user’s data in a permanent storage area. There are two kinds of files that programmers deal with text files and binary files.

Text file

Text file sometime called ASCII text file
A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. Generally it deals with character.
Since text files only process characters, they can only read or write data one character at a time. (In C Programming Language, Functions are provided that deal with lines of text, but these still essentially process data one character at a time.) A text stream in C is a special kind of file. Depending on the requirements of the operating system, newline characters may be converted to or from carriage-return/linefeed combinations depending on whether data is being written to, or read from, the file. Other character conversions may also occur to satisfy the storage requirements of the operating system. These translations occur transparently and they occur because the programmer has signalled the intention to process a text file.

Binary file

A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences.
  1. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed.
  2. C Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer.
Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. In C Programming Language, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. This indicates a second characteristic of binary files.
They a generally processed using read and write operations simultaneously.
For example, a database file will be created and processed as a binary file. A record update operation will involve locating the appropriate record, reading the record into memory, modifying it in some way, and finally writing the record back to disk at its appropriate location in the file. These kinds of operations are common to many binary files, but are rarely found in applications that process text files.

File handeling in c programming

Opening a file:
The general format of the function used for opening a file is
FILE *fp;
fp=fopen(“filename”,”mode”);
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. fopen() contain the file name and mode (the purpose of opening the file).
r is used to open the file for read only.
w is used to open the file for writing only.
a is used to open the file for appending data to it.

 Closing a File
A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. The input output library supports the function to close a file.
Syntax to close file
fclose(filepointer);

Example program for file handeling.Reading data from firstfile.txt file:-
#include
  void main(void)
   {
     FILE *myfile;
     char c;
     myfile = fopen("firstfile.txt", "r");
     if (myfile == NULL)
         printf("File doesn't exist\n");
     else {
             do {
                   c = getc(myfile);
                   putchar(c);
                  } while (c != EOF);
             }
    fclose(myfile);
   }




puzzle code of pointer

Q1) Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
      int a=10,*p,**q,***r;
      p=&a;
      q=&p;
      r=&q;
      printf("%d",*(*(*r))+5);
      getch();
}

Ans:-15

Q2) Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
int a[][3]={
             {1,2,3},
             {4,5,6},
             {7,8,9}
           };
printf("%d",  *(*(a+1)+1));     
getch();
}
Ans:-5
Discussion:-

Q3) Output of the program
#include "stdio.h"
#include "conio.h"
void print()
{
     printf("sourav");
}

main()
{
  void (*p)();    //Pointer of function declaration.
  p=print;          //Function address assignment to pointer.
  p();                 //Function call.
  getch();
}
Ans:-sourav
Discussion:-Here p is a pointer of function print(); And the print() is called by p().

Q4)Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
   int a[2][2][2]={1,2,3,4,5,6,7,8};
   printf("%d ",   *(*(*(a+1)+1)+1));
   printf("%d ",***a);
   getch();
}
Ans:-8 1
Discussion:-here a is a three dimension array. The first printf statement will print 8,the expression is equivalent to a[2][2][2] and second printf statement will print the a[0][0][0] th value of array a.
 
Q5)Is the code Wright.
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
main()
{
void *p;
p=malloc(100);
getch();
}
Ans:-No
Discussion:-To correct to coding it is need to cast the pointer.  The correct code is p=(char*)malloc(100);

Q6) Output of the program.
#include "stdio.h"
#include "conio.h"
struct abc
{
       int a,b;
 };
struct abc t,*p;
main()
{
   p=&t;
   p->a=10;
   p->b=20;
   printf("%d %d",p->a,p->b);
   getch();
}
Ans:-10 20
Discussion:-Here p is a pointer of structure. p takes the address of a structure variable .and the arrow operator(->) is used to access the member of the structure.

Q7)Output of the program.
 #include "stdio.h"
 #include "conio.h"
main()
{
   char *p="%d";   
   printf(p,500);
   getch();
}
Ans:-500
Discussion:-Here p is a character pointer. And hold the base address of the string “%d”.
In printf function p pointer replace by the string  “%d”.
Q8)Output of the program.
 #include "stdio.h"
 #include "conio.h"
main()
{
   int a[]={10,20};
   int *p=a;
   *p++;
   printf("%d ",*p);
   ++*p;
   printf("%d ",*p);
  getch();
}
Ans:-20 21
Discussion:-The statement *p++ increment the content of p pointer, so it will point the second element of array a. And the statement ++*p will increment the content of p pointer.

Q9)Output of the program.
#include "stdio.h"
#include "conio.h"
#include "string.h"
main()
{
 char *p="sourav";
 char *q="kayal";
 char a[20];
 int k=0;
 while(*p!=NULL)
 {
  a[k]=*p;
  p++;
  k++;
 }
 while(*q!=NULL)
 {
   a[k]=*q;
   q++;
   k++;            
 }
 puts(a);
 getch();
}
Ans:-souravkayal
Discussion:-This is the program of string concatenation using pointer. Here scale factor of character pointer is 1.
Q10) output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
  printf("%d %d",sizeof(NULL),sizeof(""));
  getch();
}
Ans:-It depends upon compiler.
         In xp TC++ environment it prints 2 1
         In window7 , DEV C++ environment it prints 4 1

Q11)Output of the program
#include "stdio.h"
#include "conio.h"
main()
{
   int *p;
   char *q;
   float *r;
   printf("%d %d %d",sizeof(p),sizeof(q),sizeof(r));
   getch();
}
Ans:-Output is compiler dependent
         Xp and TC combination gives 2 2 2
        Window7  and DEV C++ gives 4 4 4.
Discussion:-It depends upon system memory byte size.

Q12)Find out the error.
#include "stdio.h"
#include "conio.h"
main()
{
  int *p;
  *p=100;
  printf("%d",*p);
  getch();
}
Ans:-The program is syntactically correct. But no output will come.
Discussion:-Here p is a integer pointer but not initialize by and address. So in run time it will take random address.



 Q13)Output of program.
#include "stdio.h"
#include "conio.h"
main()
{
 
  struct abc
  {
         int a;
         int b;
  };
  struct abc t,*p;
  t.a=100;
  t.b=200;
  printf("%d",sizeof(p));
  getch();
}
Ans:-Output depends upon platform.
         In XP and TC++ it will give 2
         In Window 7 DEV C++ it will give 4
 


Concept of pointer in c programming

What is pointer?.In a nutshell.
 
Pointer is a very nice and confusing topic in c programming language. It’s nothing but a data type in case of c language. Pointers are aptly named: they "point" to locations in memory. Think of a row of safety deposit boxes of various sizes at a local bank. Each safety deposit box will have a number associated with it so that the teller can quickly look it up. These numbers are like the memory addresses of variables. A pointer in the world of safety deposit boxes would simply be anything that stored the number of another safety deposit box. Perhaps you have a rich uncle who stored valuables in his safety deposit box, but decided to put the real location in another, smaller, safety deposit box that only stored a card with the number of the large box with the real jewelry. The safety deposit box with the card would be storing the location of another box; it would be equivalent to a pointer. In the computer, pointers are just variables that store memory addresses, usually the addresses of other variables.

The cool thing is that once you can talk about the address of a variable, you'll then be able to go to that address and retrieve the data stored in it. If you happen to have a huge piece of data that you want to pass into a function, it's a lot easier to pass its location to the function than to copy every element of the data! Moreover, if you need more memory for your program, you can request more memory from the system--how do you get "back" that memory? The system tells you where it is located in memory; that is to say, you get a memory address back. And you need pointers to store the memory address.

A note about terms: the word pointer can refer either to a memory address itself, or to a variable that stores a memory address. Usually, the distinction isn't really that important: if you pass a pointer variable into a function, you're passing the value stored in the pointer--the memory address. When I want to talk about a memory address, I'll refer to it as a memory address; when I want a variable that stores a memory address, I'll call it a pointer. When a variable stores the address of another variable, I'll say that it is "pointing to" that variable.

Types of pointer
It’s having various types
1) Integet pointer
2) Character pointer
3) String pointer
4) Structure pointer
5) Pointer of union
6) Function pointer
7) File pointer
Pointers comes in two flavor  typed and untyped. A typed pointer points to a particular variable type such as an integer. An untyped pointer points to any data type. It is also called void pointer or null pointer
To declare a pointer you must put a * in front of its name.

Here is an examaple of how to declare a pointer to an integer and an untyped pointer:
int main()
{
   int *p;
   void *up;
   return 0;
}
here up pointer’s data type is void,So it is untype pointer.

You can put the address of an integer into a pointer to an integer by using the & operator to get the integer's address.
int main()
{
   int i;
   int *p;
   i = 5;
   p = &i;
   return 0;
}

You can access the value of the integer that is being pointed to by dereferencing the pointer. The * is used to dereference a pointer. Changing the value pointed to by the integer will change the value of the integer.
int main()
{
   int i,j;
   int *p;
   i = 5;
   p = &i;
   j = *p; //j = i
   *p = 7; //i = 7
   return 0;
}


Friday, January 27, 2012

puzzle code of structure

Q1) Output of the program.

#include "stdio.h"
#include "conio.h"
struct
{
       int a;
       char c;
}t[2];

main()
{
    int i; 
    printf("%d",sizeof(t));  
    getch();
}
Ans:- Compiler dependent.
Discussion:-Size of variable depends upon platform.

Q2)Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
  struct abc
   {
         int a;
         struct xyz
         {
                int b;
         }t;
   }p;
  
   p.t.b=100;
   printf("%d",t.b);
   getch();
}
Ans:-Compile time error.
Discussion:-Here xyz is a inner structure. And the scope of structure variable of inner structure is within outer structure abc. To print the member of inner structure, outer structure variable is necessary.
So the correct printf() statement is printf(“%d”,p.t.b);

 
Q3) Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
  struct hello{
                      unsigned int a:1;
                      unsigned int b:2;
                    };
  struct hello t;
  t.a=1;
  t.b=100;
  printf("%d\n",t.a);
  printf("%d",t.b);
  getch();
}
Ans:-1 0
Discussion:-The size of member b of structure hello is 2 bit. So maximum it can able to contain value 3.But here b is initialize by 100. So it will print 0.

Q4) Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
 struct hello{
               int a;
               int b;
             };
 struct hello t;
 t.a=100;
 printf("%d",t.b);
 getch();
}
Ans:-DEV C++ compiler produces error.
         TC++ compiler produces 0.
Discussion:-If structure is initialize partially then the remaining element automatically initialize by 0.



Q5) Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
 
  union hello
  {
   int a;
   int b ;
  };
  union hello t;
  t.a=10;
  printf("%d",t.b);

  getch();
}

Ans:-4
Discussion:-In Union data type, all member share a common memory. So if the value of a member is change then it affects other member.

Q6)Output of the program.

#include "stdio.h"
#include "conio.h"
main()
{
 
  union hello
  {
   int a;
   int b ;
  };
  union hello t;
  printf("%d",sizeof(t));
  getch();
}         
Ans:-DEV C++ gives 4
          TC ++ gives 2.
Discussion:-In union data type memory space is created for largest size member.


Q7)Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{    
 struct abc
 {
       int a;
       char b;
 };
struct abc p={10,'A'},q;
q=p;
printf("%d%c",q.a,q.b);
getch();
}
Ans:-10 A
Discussion:-One structure variable can initialize by other structure variable of same structure.

Q8)Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{    
struct abc{
            int a;
          }p;
struct pqr{
            int a;
          }q;
p.a=100;
q=p;         
getch();
}
Ans:-Compile time error.
Discussion:-One structure variable cannot possible to initialize by other structure variable.


Q9)Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{    
struct abc{
            int a;
          }p;
struct pqr{
            int a;
          }q;
p.a=100;
q.a=100;
if(p==q)
printf("Same");
else
printf("Not same");         
getch();
}
Ans:-Compile time error.
Discussion:-It is not allowed to compare two structure variable using == sign.


Q10) Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{    
struct abc{
            int a;
          };
struct pqr{
           struct abc p;
          }q;

q.p.a=100;
printf("%d",q.p.a);
getch();
}         
Ans:-100.
Discussion:-Here the structure variable of structure abc is declared within pqr structure .It works like nested structure.



Q11) Output of the program.
#include "stdio.h"
#include "conio.h"
struct abc
  {
         int a;
         int b;
  };

void print(struct abc *p)
{
     printf("%d%d",p->a,p->b);
}

main()
{    
  struct abc t,*p;
  t.a=10;
  t.b=20;
  p=&t;
  print(p);
  getch();
}
Ans:-10 20
Discussion:-Here the print() function takes a pointer of structure. And arrow operator (->) is used to print the member of structure.

Q12)Find error
 struct abc
  {
         int a;
         int b;
         struct abc *p
  };
Ans:-No error .
Dsicussion:-Such type of structure is called self referencing structure.


Q13)Output of the program.
#include "stdio.h"
#include "conio.h"
main()
{
      struct abc{
                  int a;
                  char b[10];
                };
      struct abc v[2]={{10,"sourav"},{100,"kayal"}};
      printf("%d%s",v.a,v.b);
      getch();
}
Ans:-Compile time error.
Discussion:-Here printf() function should be like printf(“%d%s”,v[0].a,v[0].b);