Tuesday, 12 June 2012

NOTES ON FILE HANDLING


WHAT IS FILE?



File is named location of stream of bits. It may be stored at singe place or different places but it represents a single stream. 

What is stream in c programming language?

Stream is not a hardware it is linear queue which connect file to program and passes block of data in both direction .So it is independent of devices which we are using. We can also define stream as source of data. This source can be

(a) A file
(b) Hard disk or CD, DVD etc.
(c) I/O devices etc.

In c programming language there are two type of stream.

(a) Text streams
(b) Binary streams

What is FILE pointer in c programming language?

FILE pointer is struct data type which has been defined in standard library stdio.h. This data type points to a stream or a null value. It has been defined in stdio.h as

typedef struct{
    short          level;
    unsigned       flags;
    char           fd;
    unsigned char  hold;
    short          bsize;
    unsigned char  *buffer, *curp;
    unsigned       istemp;
    short          token;
} FILE;

What is buffer in c programming language?

Buffer is a technique which reduces number of I/O call.

WRITE A C PROGRAM TO FIND SIZE OF A FILE


#include <time.h>

#include <sys\stat.h>
#include <stdio.h>
void main()
{
    struct stat status;
    FILE *fp;
    fp=fopen("test.txt","r");
    fstat(fileno(fp),&status);
    clrscr();
    printf("Size of file : %d",status.st_size);
    printf("Drive name   : %c",65+status.st_dev);
    getch();
}

Explanation:
Function int fstat (char *, struct stat *) store the information of open file in form of structure struct stat Structure struct stat has been defined in sys\stat.h as

struct stat {
    short  st_dev,   st_ino;
    short  st_mode,  st_nlink;
    int    st_uid,   st_gid;
    short  st_rdev;
    long   st_size,  st_atime;
    long   st_mtime, st_ctime;
};

Here

(a)st_dev: It describe file has stored in which drive of your computer  ,it returns a number.

(b)st_mode:  It describes various modes of file like file is read only, write only, folder, character file etc.

(c)st_size: It tells the size of file in byte.

(d)st_ctime:It tells last data of modification of the file in date format.

Note: 65 is ASCII value of A .So after adding status.st_dev with 65 it will return appropriate drvie name as in your computer.

Write a c program to find out the last date of modification.


#include <time.h>
#include <sys\stat.h>
#include <stdio.h>
void main(){
    struct stat status;
    FILE *fp;
    fp=fopen("test.txt","r");
    fstat(fileno(fp),&status);
    clrscr();
    printf("Last date of modification : %s",ctime(&status.st_ctime));
    getch();
}

Explanation:
Function int fstat(char *, struct stat *) store the  information of open file in form of  structure struct stat Structure struct stat has been defined in sys\stat.h as

struct stat {
    short  st_dev,   st_ino;
    short  st_mode,  st_nlink;
    int    st_uid,   st_gid;
    short  st_rdev;
    long   st_size,  st_atime;
    long   st_mtime, st_ctime;
};

Here

(e)st_dev: It describe file has stored in which drive of your computer.

(f)st_mode:  It describes various modes of file like file is read only, write only, folder, character file etc.

(g)st_size: It tells the size of file in byte.

(h)st_ctime:It tells last data of modification of the file in date format.

Function ctime convert date type in string format 

Write a c program to know read/write permission of given file.

#include "time.h"
#include "sys\stat.h"
#include "stdio.h"
void main(){
    struct stat status;
    FILE *fp;
    stat("test.txt",&status);
    clrscr();
    if (status.st_mode & S_IREAD)
         printf("You have read permission.\n");
    if (status.st_mode & S_IWRITE)
         printf("You have write permission.");
    getch();

}

Explanation:
Function  int stat(char *, struct stat *) store the  information of open file in form of  structure struct stat

Structure struct stat has been defined in sys\stat.h as
struct stat {
    short  st_dev,   st_ino;
    short  st_mode,  st_nlink;
    int    st_uid,   st_gid;
    short  st_rdev;
    long   st_size,  st_atime;
    long   st_mtime, st_ctime;
};
Here 

(i)st_dev: It describe file has stored in which drive of your computer.

(j)st_mode:  It describe various mode of file like file is read  only, write only, folder, character file etc.

(k)st_size: It tells the size of file in byte.

(l)St_ctime:It tells last data of modification of the file.

There are some macro has been defined in sys\stat.h

 Name          Meaning
 S_IFMT       File type mask
 S_IFDIR      Directory
 S_IFIFO      FIFO special
 S_IFCHR      Character special
 S_IFBLK      Block special
 S_IFREG      Regular file
 S_IREAD      Owner can read
 S_IWRITE     Owner can write
 S_IEXEC      Owner can execute

So masking or bit wise and operation between status.st_mode and S_IREAD return true you have read permission and so on 

What is difference between file opening mode r+ and w+ in c?




Both r+ and w+ we can read ,write on file but r+ does not truncate  (delete) the content of file  as well it doesn’t create a new file if such file doesn’t exits while in w+ truncate the content of file as well as create a new file if such file doesn’t exists.

File handling questions in c programming with solution.


(1)What will happen if you execute following program?

#include<stdio.h>
int main(){
    unsigned char c;
    FILE *fp;
    fp=fopen("test.text","r");
    while((c=fgetc(fp))!=EOF)
         printf("%c",c);
    fclose(fp);
    return 0;
}

//test.txt
I am reading file handling in cquestionbank.blogspot.com

Output: 
It will print the content of file text.txt but it will enter in infinite loop because macro EOF means -1 and at the end of file function fgetc will also return -1 but c can store only unsigned char. It will store any positive number according to rule of cyclic nature of data type. Hence condition will be always true.

(2)What will happen if you execute following program?

#include<stdio.h>
int main(){
    char *str;
    FILE *fp;
    
    fp=fopen("c:\tc\bin\test.txt","r");
    while(fgets(str,15,fp)!=NULL)
    printf("%s",str);
    fclose(fp);
    return 0;
}

//test.txt
I am reading file handling in cquestionbank.blogspot.com

Output: It will print NULL.
Explanation: As we know \ has special meaning in c programming. To store \ in a string data type there requirements of two forward slash i.e. \\. In this case fopen function will return NULL value due to wrong URL.
Right way to write that URL is: c:\\tc\\bin\\test.txt

(3)What will be output of following program?

#include<stdio.h>
int main(){
    FILE *fp;
    char *str;
    
    fp=fopen("c:\\tc\\bin\\world.txt","r");
    while(fgets(str,5,fp)!=NULL)
    puts(str);
    fclose(fp);
    return 0;
}

//world .txt
Who are you?

Output: Who a
Explanation:  It will print only first five character of including blank space of file world.txt

(4)What will happen if you execute following program?

#include<stdio.h>
int main(){
    FILE *fp1,*fp2;
    
    fp1=fopen("day.text","r");
    fp2=fopen("night.txt","r");
    fclose(fp1,fp2);
    return 0;
}

Output: Compiler error
Explanation: We cannot close more than one file using fclose function.

(5)What will be output of following program?

#include<stdio.h>
int main(){
    fprintf(stdout,"cquestionbank");
    return 0;
}

Output: cqestionbank
Explanation: stdout means standard output.

(6)What will be output of following program?

#include<stdio.h>{
    char *str="i know c .";
    
    while(*str)
    {
         putc(*str,stdout);
         fputchar(*str);
         printf("%c",*str);
         str++;
    }
    return 0;
}

Output: iii   kkknnnooowww   ccc   ...
Explanation:  We are using three functions to print or write in stream.
1.  putc is function  it can print one character on any stream. Since here stream is stdout so it will print on standard output screen.
2.  fputchar function can print one character on standard output screen.
3.  printf function can print one character on standard output screen.

(7)What will happen if you execute following program?

#include<stdio.h>
int main(){
    char c;
    FILE *fp;
    fp=fopen("d:\\rootro~1\\raja.txt","r");
    
    while((c=fgetc(fp))!=EOF)
         printf("%c",c);
    fclose(fp);
    return 0;
}

Output: It will print contain of file D:/root root/raja.txt
Explanation:  If name folder or file is more than eight characters then in URL write on first six character and add ~1 at the end of name of folder or file.

For example:
  mypicture:   mypict~1
  filehandling: fileha~1

If file or folder name contain in any blank space then remove that blank space

For example:
my photo: myphoto
program files: program~1

If two file became same then use ~2 and so on.

(8)What will be output of following program?

#include<stdio.h>
int main(){
    char c;
    FILE *fp;
    fp=fopen("d:\\rootro~1\\raja.txt","r");
    
    while((c=fgetc(fp))!=EOF){
         printf("\n%c",c);
         printf("--%d",fp->level);
    }
    fclose(fp);
    return 0;
}

//raja.txt
I love world

Output:
I--11 
 --10
l--9
o--8
v--7
e--6
 --5
w--4
o--3
r--2
l--1
d—0
Explanation:
FILE pointer is struct data type which has been defined in standard library stdio.h. It has been defined in stdio.h as

typedef struct{
    short          level;
    unsigned       flags;
    char           fd;
    unsigned char  hold;
    short          bsize;
    unsigned char  *buffer, *curp;
    unsigned       istemp;
    short          token;
} FILE;

Here level indicates how many more character have to read at particular instant.
File raja.text has total 12 character including blank space have to read at initial moment as it read raja.txt number of character also  decrease  gradually which have to read.

(9)What will be output of following program?

#include<stdio.h>
int main(){
    char c;
    FILE *fp;
    
    fp=fopen("test.txt","r");
    printf("\n %x",fp->flags);
    fp=fopen("test.txt","rb+");
    printf("\n %x",fp->flags);
    fclose(fp);
    return 0;
}

Output: 5 47
Explanation:
In stdio.h there are flag status macros which are:

  NAME   Meaning            Value (In hexadecimal)
_F_RDWR Read and write            0X0003
_F_READ Read-only file            0X0001
_F_WRIT Write-only file           0X0002
_F_BUF  Malloc'ed buffer data     0X0004
_F_LBUF Line-buffered file        0X0008
_F_ERR  Error indicator           0X0010
_F_EOF  EOF indicator             0X0020
_F_BIN  Binary file indicator     0X0040
_F_IN   Data is incoming          0X0080
_F_OUT  Data is outgoing          0X00100
_F_TERM File is a terminal        0X00200

In statement fp=fopen ("test.txt","r");
Mode of open file is read only.
So fp->flags=read only + buffer data=_F_READ+_F_BUF=1+4=5
fp=fopen("test.txt","rb+");
Mode of open file is read and writes in binary data format.
So fp->flags=read and write+ buffer data+ Binary file
=_F_RDWR+_F_BUF+_F_BIN=3+4+40=47

Note:
FILE pointer is struct data type which has been defined in standard library stdio.h. This data type points to a stream or a null value. It has been defined in stdio.h as

typedef struct{
    short          level;
    unsigned       flags;
    char           fd;
    unsigned char  hold;
    short          bsize;
    unsigned char  *buffer, *curp;
    unsigned       istemp;
    short          token;
} FILE
;

Here flags tell current status of file.

(10)What will be output of following program?

#include<stdio.h>
int main(){
    char *str;
    FILE *fp;
    fp=fopen("test.txt","r");
    fgets(str,12,fp);
    
    printf("%s",str);
    fclose(fp);
    return 0;
}

//test.txt
 Save water every day.

Output: Save water
Explanation: It will print only first 12 character including blank space from file test.txt

(11)What will be output of following program?

#include<stdio.h>
int main(){
    fprintf(&_streams[1],"www.cquestionbank.blogspot.com");
   return 0; 
}

Output: www.cquestionbank.blogspot.com
Explanation:
Array &_streams[1] is equivalent to stdout   which has been defined in stdio.h
So fprintf(stdout,"www.cquestionbank.blogspot.com"); will print the string at standard output.
Another streams array which has been defined in stdio.h  as

#define stdin     &_streams[0]
#define stdout    &_streams[1]
#define stderr     &_streams[2]
#define stdaux    &_streams[3]
#define stdprn     &_streams[4]

(12)What will be output of following program?

#include<stdio.h>
int main(){
    printf("%d",EOF);
    return 0;
}

Output: -1
Explanation: EOF is macro which has been defined in stdio.h and it is equivalent to -1

(13)What will be output of following program?

//test.c
#include<stdio.h>
int main(){
    ++EOF;
    printf("%d",EOF);
    return 0;
}

Output:  Compiler error
Explanation:
EOF is macro which has been defined in stdio.h and it is equivalent to -1. Since #define is token pasting operator which process before the start of actual compilation and create a intermediate
as: Write in command prompt

cpp test.c             //create intermediate file





type test.i             //to view intermediate file


So it replaces EOF by -1
And statement ++ (-1) is wrong in c language since we cannot increment constant value.

(14)What will be output of following program?

#include<stdio.h>
int main(){
    char c;
    FILE *fp;
    fp=fopen("myfile.txt","r+");
    fprintf(fp,"you know");
    fclose(fp);
    fp=fopen("myfile.txt","r");
    
    while((c=fgetc(fp))!=EOF)
         printf("%c",c);
    fclose(fp);
    return 0;
}
//myfile.txt
I am reading file handling from cquestionbank.blogspot.com

Output: you knowding file handling from cquestionbank.blogspot.com
Explanation:
mode r+ allow us to read and write on file and it doesn’t truncate (delete) the content of file but new content  but it starts writing from beginning of file so it will override the content of file.

(15)What will be output of following program?

#include<stdio.h>
int main(){
    char c;
    FILE *fp;
    fp=fopen("myfile.txt","w+");
    fprintf(fp,"you know");
    fclose(fp);
    fp=fopen("myfile.txt","r");
    
    while((c=fgetc(fp))!=EOF)
         printf("%c",c);
    fclose(fp);
    return 0;
}

//myfile.txt
I am reading file handling from cquestionbank.blogspot.com

Output: you know
Explanation:
Mode w+ allow us read and write on file but it truncates (delete) the previous content of file.

(16)What will be output of following program?

#include<stdio.h>
int main(){
    char c;
    FILE *fp;
    fp=fopen("myfile.txt","w");
    
    while((c=fgetc(fp))!=EOF)
         printf("%c",c);
    fclose(fp);
    return 0;
}

//myfile.txt
I am reading file handling from cquestionbank.blogspot.com

Output: nothing
Explanation:
Mode w allow us write on the file but we cannot read the content and it truncates (delete) the content of file. So content of file will be also deleted.

(17)What will be output of following program?

#include<stdio.h>
int main(){
    char c;
    FILE *fp;
    fp=fopen("myfile.txt","a");
    
    while((c=fgetc(fp))!=EOF)
         printf("%c",c);
    fclose(fp);
    return 0;
}

//myfile.txt
I am reading file handling from cquestionbank.blogspot.com

Output: NULL 
Explanation:
Mode a allow us write on file but we cannot read the content and it doesn’t truncate (delete) the content of file. So content of file will not change.

(18)What will be output of following program?

#include<stdio.h>
int main(){
    char c;
    FILE *fp;
    fp=fopen("myfile.txt","a+");
    fprintf(fp,"you know");
    fclose(fp);
    fp=fopen("myfile.txt","r");
    
    while((c=fgetc(fp))!=EOF)
         printf("%c",c);
    fclose(fp);
    return 0;
}

//myfile.txt
I am reading file handling from cquestionbank.blogspot.com

Output: I am reading file handling from cquestionbank.blogspot.comyou know
Explanation:
Mode a+ means we can read and write on file but when we will write on file it will append at the end content and it doesn’t truncate the content of file.

(19)What is difference between file opening mode rb and rb+?

Answer:
Mode rb means combination of mode r and mode b while mode rb+ means combination of mode r+ and mode b.


No comments:

Post a Comment