File Operations in C Programming Language

Rumman Ansari   Software Engineer   2019-03-31   15023 Share
☰ Table of Contents

Table of Content:


The C file system is composed of several interrelated functions. The most common of these are shown in the previous tutorial. They require the header .

Also defined in are several macros. The ones relevant to this chapter are NULL, EOF, FOPEN_MAX, SEEK_SET, SEEK_CUR, and SEEK_END.

NULL:The NULL macro defines a null pointer.

EOF:The EOF macro, often defined the value returned when an input function tries to read past the end of the file.

The File Pointer

If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the filename, data structure, purpose.

A file pointer is a pointer to a structure of type FILE. It points to information that defines various things about the file, including its name, status, and the current position of the file. In essence, the file pointer identifies a specific file and is used by the associated stream to direct the operation of the I/O functions. In order to read or write files, your program needs to use file pointers. To obtain a file pointer variable, use a statement like this:

FILE *fp;

File Operations

There are different operations that can be carried out on a file. These are below, in this section, we will discuss one by one.

  • Creation of a new file
  • Opening an existing file
  • Reading from a file
  • Writing to a file
  • Moving to a specific location in a file (seeking)
  • Closing a file

Opening a File

Before we can read (or write) information from (to) a file on a disk we must open the file. To open the file we have called the function fopen()

The general format of the function used for opening a file is

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

fopen( ) function:The fopen() function opens a stream for use and links a file with that stream. Then it returns the file pointer associated with that file.

filename:filename is a pointer to a string of characters that make up a valid filename and may include a path specification.

mode:The string pointed to by mode determines how the file will be opened.Below table shows the legal values for mode.

Mode Meaning
r Open a text file for reading
w

Create a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.

 a Append to a text file. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.
rb Open a binary file for reading
wb Create a binary file for writing
ab Append to a binary file
r+ Open a text file for read/write
w+ Create a text file for read/write. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.
a+ Append or create a text file for read/write. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
r+b Open a binary file for read/write
w+b Create a binary file for read/write
a+b Append or create a binary file for read/write

Trouble in Opening a File

There is a possibility that when we try to open a file using the function fopen( ), the file may not be opened.

 FILE *fp;
fp = fopen("test", "w");

Although the preceding code is technically correct, you will usually see it written like this:

FILE *fp;
if ((fp = fopen("test","w"))==NULL) {
printf(''Cannot open file.\n");
exit(1);
}

While opening the file in "r" mode or in "w" mode, this may happen because the file being opened may not be present on the disk at all. And you obviously cannot read a file that doesn’t exist. Similarly, while opening the file for writing, fopen() may fail due to a number of reasons, like, disk space may be insufficient to open a new file, or the disk may be write protected or the disk is damaged and so on.

FILE *fp ;
fp = fopen("file.C", "r" ) ;
if( fp == NULL )
 {
 puts( "cannot open file" ) ;
 exit( ) ;
 }

Closing a File

When we have finished reading from the file, we need to close it. there is a limit to the number of files you can have open at any one time, you may have to close one file before opening another. This is done using the function fclose().The fclose( ) function closes a stream that was opened by a call to fopen(). It writes any data still remaining in the disk buffer to the file and does a formal operating system level close on the file.


To close a file, use the fclose( ) function. The prototype of this function is ?

int fclose(FILE *fp);

he fclose() function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.

If the stream closes properly, it may invite such trouble like, including lost data, destroyed files, and possible intermittent errors in your program.

Simple Program of file

The program shown below displays use of file operations. The data enter through the keyboard and the program writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal.

Before Execuion the working folder only contain the source file that is fileprogram.c

Folder before execution

Program

  
#include<stdio.h> 
main() 
{ 
FILE *f1; 
char c;
printf("Data input output: \n"); 

f1=fopen("Input","w"); /*Open the file Input*/ 

while((c=getchar())!=EOF) /*get a character from key board*/ 
putc(c,f1); /*write a character to input*/ 
fclose(f1); /*close the file input*/ 

printf("\nData output \n"); 
f1=fopen("INPUT","r"); /*Reopen the file input*/ 
while((c=getc(f1))!=EOF) 
printf("%c",c); 

fclose(f1); 
}
 
 

Output

Data input output:
This is a file program
^Z

Data output
This is a file program
Press any key to continue . . .
 

after Execuion the working folder only contain the source file that is fileprogram.c that created earlier. also it contains the fileprogram.o, which is object file and fileprogram.exe, which is application file and the last one Input which is the expected file where we want to write.

Folder after execution

Below is our Input file and our output

Input file

Simple Program of file to write in a txt file

Before Execuion the working folder only contain the source file that is rumman.c

Folder before execution

Program

 
/* 
 *  Author: atnyla.com
 *  Description: C Write text file demo
 */
 
#include <stdio.h>
 
int main ()
{
   FILE * fp;
   int i;
   /* open the file for writing*/
   fp = fopen ("Rumman.txt","w");
 
   /* write 10 lines of text into the file stream*/
   for(i = 0; i < 10;i++){
       fprintf (fp, "This is line %d\n",i + 1);
   }
 
   /* close the file*/  
   fclose (fp);
   return 0;
}
 
 

Output

Press any key to continue . . .
 

after Execuion the working folder only contain the source file that is rumman.c that created earlier. also it contains the rumman.o, which is object file and rumman.exe, which is application file and the last one Rumman which is (.txt file) the expected file where we want to write.

Folder after execution

Below is our Rumman.txt text file and our output.

Rumman txt file