Problem Solving Through C Unit 11 File Processing Notes Set 01

Official Study Materials for Computer Science

Explore structured advanced study materials through the Problem Solving Through C Unit 11 File Processing Notes Set 01. Tailored for learners, utilizing these Computer Science resources ensures thorough preparation and strengthens foundational knowledge before final evaluations.

Advanced Resources for Computer Science

Navigate directly to the advanced Computer Science study materials using the digital viewer below. Each resource pack includes detailed conceptual summaries and solved practice questions, allowing students to instantly reinforce their learning.

This page covers file handling in C: what a file is, opening and closing files with fopen and fclose and the file modes, and the three ways of reading and writing data, namely formatted (fprintf, fscanf), character (getc, fgets, putc, fputs) and direct (fread, fwrite), followed by buffering, ftell, rewind, fseek and feof.

Concept of Files - What are files?

  • Many real-world problems handle large volume of data and in such situations external storage devices like the floppy disk and the hard disks are used.
  • Data is stored in these devices using the concept of files.
  • A file is a collection of related data stored on a particular area of the disk.

Filenames

  • Every disk file has a name, and one must use filenames when dealing with disk files.
  • Filenames are stored as strings, just like other text data.
  • The rules as to what is acceptable for filenames and what is not, differ from one operating system to another.

File Opening in Various Modes and Closing of a File

Opening a File

  • The process of creating a stream linked to a disk file is called opening the file.
  • When one opens a file, it becomes available for reading (meaning that data is input from the file to the program), writing (meaning that data from the program is saved in the file), or both.
  • After working with the file, close the file.
  • To open a file, use the fopen() library function.
void main()
{
FILE *fp;
fp=fopen("test","a");
fprintf(fp,"%d %s %d\n",1,"asdfasdf",2);
fclose(fp);
}
  • The prototype of fopen() is located in STDIO.H and it reads as follows:
  • This prototype tells the programmer that fopen() returns a pointer to type FILE, which is a structure declared in STDIO.H.
  • The members of the FILE structure are used by the program in the various file access operations; there is no need to be concerned about them.
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("abc.c", "r");
if(file==NULL)
{
   printf("Error: can't open file.\n");
   return 1;
   }
   else
   {
      printf("File opened. Now closing it...\n");
      fclose(file);
      return 0;
   }
}
  • However, for each file that has to be open, one must declare a pointer to type FILE.
  • The fopen() function creates an instance of the FILE structure and returns a pointer to that structure.
  • A programmer uses this pointer in all subsequent operations on the file.
  • If fopen() fails, it returns NULL.
  • The argument filename is the name of the file to be opened.
  • As noted earlier, filename can--and should--contain a path specification.
  • The filename argument can be a literal string enclosed in double quotation marks or a pointer to a string variable.
  • The argument mode specifies the mode in which to open the file.
  • In this context, mode controls whether the file is binary or text and whether it is for reading, writing, or both.
  • The default file mode is text.
  • Values of mode for the fopen() function.
FILE *ptrfile;
ptrfile = fopen("filename","mode");
ModeMeaning
rOpens the file for reading. If the file doesn't exist, fopen() returns NULL.
wOpens the file for writing. If a file of the specified name doesn't exist, it is created. If a file of the specified name does exist, it is deleted without warning, and a new, empty file is created.
aOpens the file for appending. If a file of the specified name doesn't exist, it is created. If the file does exist, new data is appended to the end of the file.
r+Opens the file for reading and writing. If the file doesn't exist, fopen() returns NULL. If the file does exist, new data is added to the beginning of the file, overwriting existing data.
w+Opens the file for reading and writing. If a file of the specified name doesn't exist, it is created. If the file does exist, it is overwritten.
a+Opens a file for reading and appending. If a file of the specified name doesn't exist, it is created. If the file does exist, new data is appended to the end of the file.

Different Steps to Open File

Step 1 : Declaring FILE pointer.

  • Firstly one needs pointer variable which can point to file.
  • The syntax for declaring the file pointer is.
FILE *fp;

Step 2 : Opening file hello.txt

fp = fopen ("filename","mode");

Closing a File

  • fclose() function in File Handling.
  • When a programmer opens a file in read or write mode then he performs appropriate operations on file and when file is no longer needed then he closes the file.
  • FILE close will flush out all the entries from buffer.

Important

  • After performing all Operations, FILE is no longer needed.
  • File is closed using fclose() function.
  • All information associated with file is flushed out of buffered.
  • Closing file will prevent misuse of FILE.

Syntax : fclose()

int fclose(FILE *fp);

Simple Example

#include<stdio.h>

int main()
{
FILE *fp;

fp = fopen("INPUT.txt","r");

  -----------
  -----------
  -----------
  -----------

fclose(fp); //File is no longer needed
}

Writing and Reading File Data

  • A program that uses a disk file can write data to a file, read data from a file, or a combination of the two.
  • One can write data to a disk file in three ways:
  • First way: One can use formatted output to save formatted data to a file. One should use formatted output only with text-mode files. The primary use of formatted output is to create files containing text and numeric data to be read by other programs such as spreadsheets or databases.
  • Second way: One can use character output to save single characters or lines of characters to a file. Although technically it's possible to use character output with binary-mode files, it can be tricky. One should restrict character-mode output to text files. The main use of character output is to save text (but not numeric) data in a form that can be read by C, as well as other programs such as word processors.
  • Third way: One can use direct output to save the contents of a section of memory directly to a disk file. This method is for binary files only. Direct output is the best way to save data for later use by a C program.
  • When one wants to read data from a file, he has the same three options: formatted input, character input, or direct input.
  • The type of input one would use in a particular case depends almost entirely on the nature of the file being read.
  • The data will be read in the same mode that it was saved in, but this is not a requirement.

Formatted File Input and Output

  • Formatted file input/output deals with text and numeric data that is formatted in a specific way.
  • It is directly analogous to formatted keyboard input and screen output done with the printf() and scanf() functions.

Formatted File Output

  • Formatted file output is done with the library function fprintf().
  • The prototype of fprintf() is in the header file STDIO.H, and it reads as follows:
int fprintf(FILE *fp, char *fmt, ...);
  • The first argument is a pointer to type FILE.
  • To write data to a particular disk file, pass the pointer that was returned when the file was opened with fopen().
  • The second argument is the format string.
  • The format string used by fprintf() follows exactly the same rules as printf().
  • In other words, in addition to the file pointer and the format string arguments, fprintf() takes zero, one, or more additional arguments.
  • This is just like printf(). These arguments are the names of the variables to be output to the specified stream.
  • Remember, fprintf() works just like printf(), except that it sends its output to the stream specified in the argument list.

Formatted File Input

  • For formatted file input, use the fscanf() library function, which is used like scanf(), except that input comes from a specified stream instead of from stdin.
  • The prototype for fscanf() is:
int fscanf(FILE *fp, const char *fmt, ...);
  • The argument fp is the pointer to type FILE returned by fopen(), and fmt is a pointer to the format string that specifies how fscanf() is to read the input.
  • The components of the format string are the same as for scanf().
  • Finally, the ellipses (...) indicate one or more additional arguments, the addresses of the variables where fscanf() is to assign the input.

Character Input and Output

  • When used with disk files, the term character I/O refers to single characters as well as lines of characters.
  • The line is a sequence of zero or more characters terminated by the newline character.
  • Use character I/O with text-mode files.

Character Input

  • There are three character input functions: getc() and fgetc() for single characters, and fgets() for lines.
  • The functions getc() and fgetc() are identical and can be used interchangeably.
  • They input a single character from the specified stream.
  • Here is the prototype of getc(), which is in STDIO.H:
int getc (FILE *fp);
  • The argument fp is the pointer returned by fopen() when the file is opened.
  • The function returns the character that was input or EOF on error.
  • getc() was used in earlier programs to input a character from the keyboard.
  • This is another example of the flexibility of C's streams--the same function can be used for keyboard or file input.

The getc() Function - Program

#include <stdio.h>
int main ()
{
   FILE *fp;
   int c;
   int n = 0;

   fp = fopen("file.txt","r");
   if(fp == NULL)
   {
      perror("Error in opening file");
      return(-1);
   }
   do
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
         break ;
      }
      printf("%c", c);
   }while(1);

   fclose(fp);
   return(0);
}

The fgets() Function

  • To read a line of characters from a file, use the fgets() library function.
  • The prototype is: char *fgets(char *str, int n, FILE *fp);
  • The argument str is a pointer to a buffer in which the input is to be stored, n is the maximum number of characters to be input, and fp is the pointer to type FILE that was returned by fopen() when the file was opened.
  • When called, fgets() reads characters from fp into memory, starting at the location pointed to by str.
  • Characters are read until a newline is encountered or until n-1 characters have been read, whichever occurs first.
  • By setting n equal to the number of bytes allocated for the buffer str, one prevents input from overwriting memory beyond allocated space. (The n-1 is to allow space for the terminating \0 that fgets() adds to the end of the string).
  • If successful, fgets() returns str.
#include <stdio.h>
int main()
{
   FILE *fp;
   char str[60];

   /* opening file for reading */
   fp = fopen("file.txt" , "r");
   if(fp == NULL) {
      perror("Error opening file");
      return(-1);
   }
   if( fgets (str, 60, fp)!=NULL ) {
      /* writing content to stdout */
      puts(str);
   }
   fclose(fp);

   return(0);
}

The putc() Function

  • The library function putc() writes a single character to a specified stream.
  • Its prototype in STDIO.H is as shown below:
int putc(int ch, FILE *fp);
  • The argument ch is the character to output.
  • As with other character functions, it is formally called a type int, but only the lower-order byte is used.
  • The argument fp is the pointer associated with the file (the pointer returned by fopen() when the file was opened).
  • The function putc() returns the character just written if successful or EOF if an error occurs.
  • The symbolic constant EOF is defined in STDIO.H, and it has the value -1.
  • Because no "real" character has that numeric value, EOF can be used as an error indicator (with text-mode files only).

The fputs() Function

  • To write a line of characters to a stream, use the library function fputs().
  • This function works just like puts().
  • The only difference is that with fputs() one can specify the output stream.
  • Also, fputs() doesn't add a newline to the end of the string; one must explicitly include it.
  • Its prototype in STDIO.H is:
int fputs(char *str, FILE *fp);
  • The argument str is a pointer to the null-terminated string to be written, and fp is the pointer to type FILE returned by fopen() when the file was opened.
  • The string pointed to by str is written to the file, minus its terminating \0.
  • The function fputs() returns a non-negative value if successful or EOF on error.
#include <stdio.h>

int main ()
{
   FILE *fp;

   fp = fopen("file.txt", "w+");

   fputs("This is c programming.", fp);
   fputs("This is a system programming language.", fp);

   fclose(fp);

   return(0);
}

Direct File Input and Output

  • The direct file I/O is used most often when one has to save data to be read later by the same or a different C program.
  • Direct I/O is used only with binary-mode files.
  • With direct output, blocks of data are written from memory to disk.
  • Direct input reverses the process: A block of data is read from a disk file into memory.
  • For example, a single direct-output function call can write an entire array of type double to disk, and a single direct-input function call can read the entire array from disk back into memory.
  • The direct I/O functions are fread() and fwrite().

The fwrite() Function

  • The fwrite() library function writes a block of data from memory to a binary-mode file.
  • Its prototype in STDIO.H is:
int fwrite(void *buf, int size, int count, FILE *fp);
  • The argument buf is a pointer to the region of memory holding the data to be written to the file.
  • The pointer type is void; it can be a pointer to anything.
  • The argument size specifies the size, in bytes, of the individual data items, and count specifies the number of items to be written.
  • The argument fp is, of course, the pointer to type FILE, returned by fopen() when the file was opened.
  • The fwrite() function returns the number of items written on success; if the value returned is less than count, it means that an error has occurred.

The fwrite() Function - Program

#include<stdio.h>
int main ()
{
   FILE *fp;
   char str[] = "hello turbo c ";

   fp = fopen( "file.txt" , "w" );
   fwrite(str , 1 , sizeof(str) , fp );

   fclose(fp);

   return(0);
}

The fread() Function

  • The fread() library function reads a block of data from a binary-mode file into memory.
  • Its prototype in STDIO.H is:
int fread(void *buf, int size, int count, FILE *fp);
  • The argument buf is a pointer to the region of memory that receives the data read from the file.
  • As with fwrite(), the pointer type is void.
  • The argument size specifies the size, in bytes, of the individual data items being read, and count specifies the number of items to read.
  • Note how these arguments parallel the arguments used by fwrite().
  • Again, the sizeof() operator is typically used to provide the size argument.
  • The argument fp is the pointer to type FILE that was returned by fopen() when the file was opened.
  • The fread() function returns the number of items read; this can be less than count if end-of-file was reached or an error occurred.

The fread() Function - Program

#include <stdio.h>
#include <string.h>
int main()
{
  FILE *fp;
  char c[] = "this is a program";
  char buffer[20];

 /* Open file for both reading and writing */
 fp = fopen("file.txt", "w+");
  /* Write data to the file */
 fwrite(c, strlen(c) + 1, 1, fp);

  /* Seek to the beginning of the file */
 fseek(fp, 0, SEEK_SET);

  /* Read and display data */
 fread(buffer, strlen(c)+1, 1, fp);
  printf("%s\n", buffer);
 fclose(fp);

 return(0);
}

File Buffering: Closing and Flushing Files

  • When one has done with using a file, one should close it using the fclose() function.
  • The fclose() prototype is as shown below
int fclose(FILE *fp);
  • The argument fp is the FILE pointer associated with the stream; fclose() returns 0 on success or -1 on error.
  • When one closes a file, the file's buffer is flushed (i.e. written to the file).
  • One can also close all open streams except the standard ones (stdin, stdout, stdprn, stderr, and stdaux) by using the fcloseall() function.
  • Its prototype is as shown below:
int fcloseall(void);
  • This function also flushes any stream buffers and returns the number of streams closed.
  • When a program terminates (either by reaching the end of main() or by executing the exit() function), all streams are automatically flushed and closed.
  • However, it's a good idea to close streams explicitly--particularly those linked to disk files.

The ftell() and rewind() Functions

  • To set the position indicator to the beginning of the file, use the library function rewind().
  • Its prototype, in STDIO.H, is:
void rewind(FILE *fp);
  • The argument fp is the FILE pointer associated with the stream.
  • After rewind() is called, the file's position indicator is set to the beginning of the file (byte 0).
  • The rewind() is used to read some data from the beginning of the file again without closing and reopening the file.

The ftell() and rewind() Functions

  • To determine the value of a file's position indicator, use ftell().
  • This function's prototype, is located in STDIO.H and reads as follows:
long ftell(FILE *fp);
  • The argument fp is the FILE pointer returned by fopen() when the file was opened.
  • The function ftell() returns a type long that gives the current file position in bytes from the start of the file (the first byte is at position 0).
  • If an error occurs, ftell() returns -1 (of type long).

fseek() Function

  • More precise control over a stream's position indicator is possible with the fseek() library function.
  • By using fseek(), one can set the position indicator anywhere in the file.
  • The function prototype, in STDIO.H, is as follows:
int fseek(FILE *fp, long offset, int origin);
  • The argument fp is the FILE pointer associated with the file.
  • The distance that the position indicator is to be moved is given by its offset in bytes.
  • The argument origin specifies the move's relative starting point.
  • There can be three values for origin, with symbolic constants defined in STDIO.H
ConstantValueOrigin
SEEK_SET0Beginning of the file
SEEK_CUR1Current position
SEEK_END2End of the file

feof() Function

  • With a binary-mode stream, one can't detect the end-of-file by looking for -1, because a byte of data from a binary stream could have that value, which would result in a premature end of input.
  • Instead the library function feof() can be used, which can be used for both binary- and text-mode files as shown below:
int feof(FILE *fp);
  • The argument fp is the FILE pointer returned by fopen() when the file was opened.
  • The function feof() returns 0 if the end of file fp hasn't been reached, or a nonzero value if end-of-file has been reached.
  • If a call to feof() detects end-of-file, no further read operations are permitted until a rewind() has been done, fseek() is called, or the file is closed and reopened.

Free CBSE Study Guides: Computer Science Programming in C

Quick Revision Material for Programming in C

Review targeted study resources for Programming in C tailored for learners. Utilizing these structured notes and quick-revision tools ensures complete alignment with current CBSE evaluation standards.

Expert Notes and Solved Exam Questions

Built using official NCERT guidelines for Computer Science, these materials provide reliable academic support. Integrating past examination questions and step-by-step solutions helps students understand official CBSE grading criteria.

Additional Study Resources for

Wrap up your chapter revision by testing your knowledge against standard objective question formats. Explore our full library of free, up-to-date sample papers and online assessments to secure top grades in your CBSE examinations.

FAQs

Where can I find the most advanced study material for [current-page:node:field_board] [current-page:node:field_class] Computer Science for 2026-27?

The latest 2026-27 advanced study resources for Computer Science are available for free on StudiesToday.com which includes NCERT Exemplars, high-order thinking skills (HOTS) questions, and deep-dive concept summaries.

What does the 2026-27 Computer Science study package for [current-page:node:field_class] include?

Our exhaustive Computer Science package includes chapter wise revision notes, solved practice sheets, important formulas and Concept Maps to help in better understanding of all topics.

Is this study material enough for both [current-page:node:field_board] exams and competitive tests?

Yes. For , our resources have been developed to help you get better marks in school exams and also build fundamental strength needed for entrance tests including Competency Based learning.

How should [current-page:node:field_class] students use this Computer Science material for maximum marks?

in , students should use Active Recall method, read the concept summary, then solve the Important Questions section without looking at the answers and then check your answers.

Can I download [current-page:node:field_class] Computer Science study notes in PDF for offline use?

All Computer Science study materials are provided in mobile-friendly PDF. You can download and save them on your device.

Are the [current-page:node:field_class] Computer Science resources updated for the latest NEP guidelines?

Yes, our team has ensured that all Computer Science materials for are strictly aligned with the National Education Policy (NEP) 2020 and the latest 2026-27 syllabus.