Learning C/C++ Step-By-Step - Page 12

Want to support HowtoForge? Become a subscriber!
Submitted by ganesh35 (Contact Author) (Forums) on Wed, 2009-01-07 18:38. ::

12. Step-by-Step CorC++ --- C Programming - Files

File Handling


Let’s find the output of the following program.


Yes, it accepts a record of student information and displays it.
Here is the same program, but included statements with a few modifications.


Above two programs are same, but the second program contains a highlighted statement (FILE *fp = fopen(“stud.dat”, “a+”); ) and a few modifications like ‘fprintf’, ‘fp’. Only few modifications included. These modifications affect data to transfers from console to diskette in the file stud.dat. This process is known as file control/file management/file organization.

This is an easiest way to transfer the output from monitor to file using file control statement.


Actually file processing involved with a lot of operations as well as methods to implement. Here is the actual process to handle files.


File Handling

Generally every program has to present the resulted values on the screen (1st program illustrates this). But those values are removed from the memory whenever the program is terminated. If we want to keep records permanently, save them in a file. Every file has a few operations, here is a few;


File Operations


Opens the stream filename in the mode mode & if succeeded, Returns a pointer to the newly open stream; or Null other wise.


FILE *fopen(const char *filename, const char *mode);


FILE *fp = fopen("stud.dat", "r");   /*  Read from file  */
FILE *fp = fopen("emp.dat", "w"); /*  Write to file  */
FILE *fp = fopen("emp.dat", "a+");           /*  Read and Write on file */


The mode string used in calls to fopen, is one of the following values:

       Mode     Description

r           Open for reading only
w         Create for writing (If a file by that name already exists, it will be overwritten).
a     Append; open for writing at end of file, or create for
                        writing if the file does not exist.
            r+    Open an existing file for update (reading and writing)
            w+    Create a new file for update (reading and writing).
If a file by that name already exists, it will be overwritten.
            a+    Open for append; open for update at the end of the file, or
                        create if the file does not exist.

To specify that a given file is being opened or created in text mode,
             append "t" to the string (rt, w+t, etc.).
To specify binary mode, append "b" to the string (wb, a+b, etc.).


Closes the file pointed to by fp & returns 0 on success, EOF is returned in case of error


Int fclose(FILE *fp);


Fclose(fp);  fclose(stud);   fcloseall();


Sends formatted output to a stream. Uses the same format specifiers as printf, but sends output to the specified stream. Returns the number of bytes output or EOF in case of error.


Fprintf(fptr, “Control String”, list);


Fprintf(fp, “%d %s %d %d %d”, sno, name, sub1, sub2, sub3);
fprintf(emp, “%d %s %d”, eno, name, sal);


This function is used to read a formatted data from a specified file.


Fscanf(fptr, “Control String”, list);


Fscanf(fp, “%d %s %d %d %d”, &sno, name, &sub1, &sub2, &sub3);
fscanff(emp, “%d %s %d”, &eno, name, &sal);


Fwrite appends a specified number of equal-sized data items to an output file.


Size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
Argument  What It Is/Does
  Ptr       Pointer to any object; the data written begins at ptr
  Size     Length of each item of data
  N          Number of data items to be appended
  stream   Specifies output file
  The total number of bytes written is  (n * size)


Fread retrieves a specified number of equal-sized data items from an input file.


Size_t fread(void *ptr, size_t size, size_t n, FILE*stream);
Argument  What It Is/Does
  Ptr      Pointer to any object; the data written begins at ptr
  size     Length of each item of data
  n        Number of data items to be appended
  stream   Specifies output file
 The total number of bytes written is (n * size)


Repositions file pointer to stream's beginning


Void rewind(FILE *stream);
E.g.      fewind(fp);
Rewind(stream) is equivalent to fseek(stream, 0L, SEEK_SET)
except that rewind clears the end-of-file and error indicators, while fseek only clears the end-of-file indicator. After rewind, the next operation on an update file can be either input or output.


The file pointer for the stream is positioned at offset number of bytes calculated from the position specified by whence. Offset may be zero, negative, or positive. The defined symbols SEEK_CUR, SEEK_SET & SEEK_END are used as whence specifiers to indicate current position. BOF & EOF respectively. Returns 0 if successful or nonzero on failure.


Int fssek(FILE *stream, long offset, int whence);


Returns the current file pointer position on success or Negative value on error.


Long ftell(FILE *stream);


It is a macro to return nonzero if end-of-file has been reached on the stream.


Int feof(FILE *stream);


Checks whether the position marker in the file given by its handle is at the end-of-file. If yes, returns 0, 1 is returned if position marker is NOT at eof & an error is indicated by setting of errno & return value of –1.


Int eof(int handle);

fgets /

The function fgets/fputs gets/puts a string(of size n bytes) on the file pointed to by stream and returns end-of-file on error.


Char *fgets(char *s, int n, FILE *stream);


Reads/writes a character from a stream.
Int fgetc/fputc(FILE *stream);


These are equivalent to the above fgetc/fputc.

Write a program to read a student data and store it in a data file.


/* Program to create a student data file */
/* 85_write.c */
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main()
      int sno, sub1, sub2, sub3;
      char name[10],ch;
      FILE *fp = fopen("stud.dat", "w");
            printf("Enter Student number        "); scanf("%d", &sno);
            printf("Enter Student name          "); scanf("%s", name);
            printf("Enter 3 Subjects Marks      ");
            scanf("%d%d%d", &sub1, &sub2, &sub3);
            fprintf(fp, "%d %s %d %d %d\n", sno, name, sub1, sub2, sub3);
            printf("\n\nDo you want to cont... (y/n)"); ch = getche();
      }while(toupper(ch) != 'N');
      return 0;

Write a program to retrieve data from a student data file.


/* Program to retrieve data from a student data file */
/* 86_read.c */
#include <stdio.h>
#include <conio.h>
int main()
      int sno, sub1, sub2, sub3;
      char name[10];
      FILE *fp = fopen("stud.dat", "a+");
      printf("Student Records are as follows....\n");
            fscanf(fp, "%d%s%d%d%d\n", &sno, name, &sub1, &sub2, &sub3);
            printf("%5d%15s%3d%3d%3d\n", sno, name, sub1, sub2, sub3);
      return 0;

Please do not use the comment function to ask for help! If you need help, please use our forum.
Comments will be published after administrator approval.