Users Online

· Guests Online: 40

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#C PROGRAMMING LANGUAGE TUTORIALS

Files Handling - C Programming

 

 

1. File Pointers

There are many ways to use files in C. The most straight forward use of files is via a file pointer.

FILE *fp; 

fp is a pointer to a file.

The type FILE, is not a basic type, instead it is defined in the header file stdio.h, this file must be included in your program.

2. Opening a File

fp = fopen(filename, mode);

The filename and mode are both strings.

The mode can be

  • r - read
  • w - write, overwrite file if it ex ists
  • a - write, but append instead of overwrite
  • r+ - read & write, do not destroy file if it exists
  • w+ - read & write, but overwrite file if it exists
  • a+ - read & write, but append instead of overwrite
  • b - may be appended to any of the above to force the file to be opened in binary mode rather than text mode
  • fp = fopen("data.dat","a"); - will open the disk file data.dat for writing, and any information written will be appended to the file.

The following useful table from the ANSI C Rationale lists the different actions and requirements of the different modes for opening a file:

fopen returns NULL if the file could not be opened in the mode requested. The returned value should be checked before any attempt is made to access the file. The following code shows how the value returned by fopen might be checked. When the file cannot be opened a suitable error message is printed and the program halted. In most situations this would be inappropriate, instead the user should be given the chance of re-entering the file name.

#include <stdio.h>
int main()
{
    char filename[80];
    FILE *fp;
    printf("File to be opened? ");
    scanf("%79s", filename);
    fp = fopen(filename,"r");
    if (fp == NULL)
    {
        fpri ntf(stderr, "Unable to open file %s\n", filename);
        return 1; /* Exit to operating system */
    }
    //code that accesses the contents of the file
    return 0;
}

Sequential file access is performed with the following library functions.

  • fprintf(fp, formatstring , ...) - print to a file
  • fscanf(fp, formatstring , ...) - read from a file
  • getc(fp) - get a character from a file
  • putc(c, fp) - put a character in a file
  • ungetc(c, fp) - put a character back onto a file (only one character is guaranteed to be able to be pushed back)
  • fopen( filename , mode) - open a file
  • fclose(fp) - close a file

The standard header file stdio.h defines three file pointer constants, stdin ,stdout and stderr for the standard input, output and error streams. It is considered good practice to write error messages to the standard error stream.

Use the fprintf() function to do this:

fprintf(stderr,"ERROR: unable to open file %s\n", filename);

The functions fscanf() and getc() are used for sequential access to the file, that is subsequent reads will read the data following the data just read, and eventually you will reach the end of the file. If you want to move forwards and backwards through the file, or jump to a specific offset from the beginning, end or current location use the fseek() function (though the file mustbe opened in binary mode). The function ftell() reports the current offset from the beginning of the file.

If you wish to mix reading and writing to the same file, each switch from reading to writing (or vice versa) mustbe preceded by a call to fseek()fsetpos()rewind() or fflush(). If it is required to stay at the same position in the file then use fflush() or fseek(fp,0L,SEEK_CUR) which will move 0 bytes from the current position!

 

3. Examples

 

EXAMPLE STATEMENT FOR FILES HANDLING IN C LANGUAGE

 

1. Illustrate as to how the data stored on the disk is read

 

/**********************************************************
 Statement - Illustrate as to how the data stored on the disk is read
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 **********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void main()
{
    FILE *fptr;
    char filename[15];
    char ch;
    clrscr();
    
    printf("Enter the filename to be opened\n");
    gets(filename);
    
    fptr = fopen (filename, "r");  /*open for reading*/
    
    if (fptr == NULL)
    {
        printf("Cannot open file\n");
        exit(0);
    }
    
    ch = fgetc(fptr);
    
    while (ch != EOF)
    {
        printf ("%c", ch);
        ch = fgetc(fptr);
    }
    
    fclose(fptr);
    getch();
}   					/* End of main () */
/*----------------------------------------------
 Output
 Enter the filename to be opened
 emp.rec
 Name    = Prabhu
 Age     = 25
 Salary  = 25000.00
 ------------------------------------------------*/

 

 

2. Write static data in file and read from file

 

 

/**********************************************************
 Statement - Write static data in file and read from file
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 **********************************************************/


#include<stdio.h>
#include<conio.h>

struct Student {
    int roll;
    char name[12];
    int percent;
} s1 = { 96, "VINEET", 76 };

void main() {
    FILE *fp;
    struct Student s2;
    clrscr();
    
    //Write details of s1 to file
    fp = fopen("ip.txt", "w");
    fwrite(&s1, sizeof(s1), 1, fp);
    fclose(fp);
    
    //Read saved details from file
    fp = fopen("ip.txt", "r");
    fread(&s2, sizeof(s2), 1, fp);
    fclose(fp);
    
    printf("\nRoll : %d", s2.roll);
    printf("\nName : %s", s2.name);
    printf("\nPercent : %d", s2.percent);
    
    getch();
}


Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.72 seconds
10,272,264 unique visits