Thursday, July 14, 2011

FILE HANDELING

FILE HANDELING

File Input and Output


Library Functions for File I/O.

fopen is used to open a file for formatted I/O and to associate a stream with that file. A stream is a source or destination of data. It may be a buffer in memory, a file or some hardware device such as a port.
FILE *fp;
fp=fopen(filename, mode);
fopen() returns a file pointer on success or NULL on failure. The file pointer is used to identify the stream and is passed as an argument to the routines that read, write or manipulate the file. The filename and mode arguments are standard null-terminated strings. The valid modes are shown below.
Mode Use
"r" Read Mode.If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn't  exist it returns NULL.
Operations Possible:- reading from the file
"w" Write Mode. If the file exists, its contents are overwritten. If the file doesn't exist, a new file is created. Returns NULL, if unable to open file.
Operations Possible:- writing to the file
"a" Append Mode. If the file exists, loads it into memory and sets up a pointer that points to the last character in it. If the file doesn't exist, a new file is created. Returns NULL, if unable to open file
Operations Possible:- adding new contents at the end of file
"r+" Read Plus Mode. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn't  exist it returns NULL.
Operations Possible:- reading existing contents, writing new contents, modifying existing contents of the file
"w+" Write Plus Mode. If the file exists, its contents are destroyed. If the file doesn't exist, a new file is created. Returns NULL, if unable to open file.
Operations Possible:- writing new contents, reading them back and modifying existing contents of the file
"a+" Append Plus Mode. If the file exists, loads it into memory and sets up a pointer that points to the first character in it. If the file doesn't exist, a new file is created. Returns NULL, if unable to open file
Operations Possible:- reading existing contents, appending new contents to the end of file. Cannot modify existing contents.
Files are closed with the function fclose. Its prototype is:
fclose(*fp);

Functions for Reading and Writing to the file

fprintf():

Data is written to a file using fprintf. This function is very similar to printf. Printf was used to write to standard output, stdout. Fprintf has one additional argument to specify the stream to send data. Its prototype is:
fprintf(FILE *stream, const char* format, ....);

fscanf():

Data is read from a file using fscanf. This function is very similar to scanf, is used to read from standard input, stdin. Fscanf has one additional argument to specify the stream to read from. Remember that the argument to store data must be pointers.
fscanf(FILE *stream, const char* format, ....);

Other Useful Standard Library Functions for Input and Output

int fgetc(FILE *stream);
This function returns the next character in the input stream, or EOF if the end of the file is encountered. It returns int rather than char because the "end of file", EOF, character must be handled. EOF is an int and is too large to fit in a char variable.
int *fgets(char *s, int n, FILE *stream);
It returns a pointer to the character string if successful, or NULL if end of file is reached or if an error has occurred. The string is also read into the character array specified as an argument. The character string will be terminated be a "\0", which is standard for C.
At most n-1 characters will be read. This allows for storage of the string terminator, '\0'.
fputs(const char s*, FILE *stream);
This function writes a string to the stream. It returns EOF on failure.
int fputc(int c, FILE *stream);
fputc writes a single character to the output stream i.e. file. It returns EOF on failure.
int sprintf(char *buffer, const char *format, ...);
This function is the same as fprintf, except data is written into a character buffer rather than an output stream.
int sscanf(char *buffer, const char *format, ...);
This function is the same as fscanf, except data is read from a character buffer rather than an input stream.

Example 1: Here is the example program which creates a file "Record.txt" and adds students record in it.
#include<stdio.h>

main()
{
    char name[30];
    int idNum;
    FILE *fp;

    /* Open file for input */
    fp = fopen("Record.txt","w");
if(fp==NULL)
{
    printf("Error Opening File !!!");
    exit(1);
}
 
printf("Enter name and id")
scnaf("%d %s", name, &idNum);
 
/* Write out data */
fprintf(fp,"%d %s\n",idNum, name);
 
/* Close Files */
fclose(fp);
}
Example 2: Here is the example program which reads name and id form student record a file "Record.txt" and displays on screen.
#include<stdio.h>

main()
{
    char name[30];
    int idNum;
    FILE *fp;

    /* Open file for read */
    fp = fopen("Record.txt","r");
if(fp==NULL)
{
      printf("Error Opening File !!!");
      exit(1);
}
/*reading all records form file */
while(fscanf(fp,"%d %s", &idNum, name) != EOF)
          printf("%d %s\n", idNum, name);
 
/* Close Files */
fclose(fp);
}
Example: Create a file name "COLLEGE.DAT". Write a program to store record of n students in a file. These records contain student name, roll no, program. Also display records of those students whose program is BBAII and BCA II.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define N 2 //defining the N no. of student
void main()
{  
    struct student
    {
          int roll_no;
          char name[25],program[25];            
    };
    struct student s;
    int i;
    FILE *fp;
 
    fp = fopen ("COLLEGE.DAT ", "w+");
    if (fp == NULL);
    {
          puts("Cannot open file");          
          exit(0);
    }    
    //taking student records as input and writing it into file
    for(i=0;i<N;i++)
    {
          scanf("%d %s %s %d",&s.roll_no,s.name, s.program);
          fwrite(&s,sizeof(s),1,fp);//writing record into file
    }
   
    //reading from file until end of file
    while(fread(&s,sizeof(s),1,fp)!=EOF)
    {    
          //displaying only those records having program is BBAII or BCAII
          if(strcmp(s.program,"BBAII")==0||strcmp(s.program,"BCAII")==0)
                printf("%d\t %s\t %s\n",s.roll_no,s.name,s.program); 
    }    
    fclose(fp);
    getch();
}

0 comments:

Post a Comment