0% found this document useful (0 votes)
109 views

File Handling

C provides functions for file handling such as opening, closing, reading, and writing files. There are two types of files - text files containing ASCII codes and binary files containing bytes. Functions like fopen(), fclose(), fprintf(), and fscanf() are used to open, close, write to, and read from files. Files can be opened in different modes like read, write, and append which determine if the file can be read from or written to. Error handling in C uses functions returning values like -1 or NULL to indicate errors and the global errno variable to store the error code.

Uploaded by

Bushra TaTa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

File Handling

C provides functions for file handling such as opening, closing, reading, and writing files. There are two types of files - text files containing ASCII codes and binary files containing bytes. Functions like fopen(), fclose(), fprintf(), and fscanf() are used to open, close, write to, and read from files. Files can be opened in different modes like read, write, and append which determine if the file can be read from or written to. Error handling in C uses functions returning values like -1 or NULL to indicate errors and the global errno variable to store the error code.

Uploaded by

Bushra TaTa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

File handling --- https://www.guru99.com/c-file-input-output.

html

https://fresh2refresh.com/c-programming/c-file-handling/

C File management

A File can be used to store a large volume of persistent data. Like many other languages 'C' provides following file management functions,

1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file

There are two kinds of files in a system. They are,

1. Text files (ASCII)


2. Binary files
 Text files contain ASCII codes of digits, alphabetic and symbols.
 Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of text
files.
Following are the most important file management functions available in 'C,'

function purpose

fopen () Creating a file or opening an existing file

fclose () Closing a file

fprintf () Writing a block of data to a file

fscanf () Reading a block data from a file

getc () Reads a single character from a file

putc () Writes a single character to a file

getw () Reads an integer from a file

putw () Writing an integer to a file

fseek () Sets the position of a file pointer to a specified location

ftell () Returns the current position of a file pointer

rewind () Sets the file pointer at the beginning of a file

File operation Declaration & Description

fopen() – To open Declaration: FILE *fopen (const char *filename, const char *mode)
a file fopen() function is used to open a file to perform operations such as reading, writing etc. In a C program, we
declare a file pointer and use fopen() as below. fopen() function creates a new file if the mentioned file name does
not exist.
FILE *fp;
fp=fopen (“filename”, ”‘mode”);
Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+ and a+. Please refer
below the description for these mode of operations.

Declaration: int fclose(FILE *fp);
fclose() – To close fclose() function closes the file that is being pointed by file pointer fp. In a C program, we close a file as below.
a file fclose (fp);

Declaration: char *fgets(char *string, int n, FILE *fp)


fgets function is used to read a file line by line. In a C program, we use fgets function as below.
fgets (buffer, size, fp);
where,
buffer – buffer to  put the data in.
fgets() – To read a size – size of the buffer
file fp – file pointer

Declaration:
int fprintf(FILE *fp, const char *format, …);fprintf() function writes string into a file pointed by fp. In a C
program, we write string into a file as below.
fprintf() – To write fprintf (fp, “some data”); or
into a file fprintf (fp, “text %d”, variable_name);

MODE OF OPERATIONS PERFORMED ON A FILE IN C LANGUAGE:


There are many modes in opening a file. Based on the mode of file, it can be opened for reading or writing or
appending the texts. They are listed below.

 r – Opens a file in read mode and sets pointer to the first character in the file. It returns null if file
does not exist.
 w – Opens a file in write mode. It returns null if file could not be opened. If  file exists, data are
overwritten.
 a – Opens a file in append mode.  It returns null if file couldn’t be opened.
 r+ – Opens a file for read and write mode and sets pointer to the first character in the file.
 w+ – opens a file for read and write mode and sets pointer to the first character in the file.
 a+ – Opens a file for read and write mode and sets pointer to the first character in the file. But, it
can’t modify existing contents.

INBUILT FUNCTIONS FOR FILE HANDLING IN C LANGUAGE:


C programming language offers many inbuilt functions for handling files. They are given below. Please click on
each function name below to know more details, example programs, output for the respective file handling
function.

File handling functions Description

fopen () fopen () function creates a new file or opens an existing file.

fclose () fclose () function closes an opened file.

getw () getw () function reads an integer from file.

putw () putw () functions writes an integer to file.

fgetc () fgetc () function reads a character from file.

fputc () fputc () functions write a character to file.


gets () gets () function reads line from keyboard.

puts () puts () function writes line to o/p screen.

fgets () fgets () function reads string from a file, one line at a time.

fputs () fputs () function writes string to a file.

feof () feof () function finds end of file.

fgetchar () fgetchar () function reads a character from keyboard.

fprintf () fprintf () function writes formatted data to a file.

fscanf () fscanf () function reads formatted data from a file.

fputchar () fputchar () function writes a character onto the output screen from keyboard input.

fseek () fseek () function moves file pointer position to given location.

SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.

SEEK_CUR SEEK_CUR moves file pointer position to given location.

SEEK_END SEEK_END moves file pointer position to the end of file.

ftell () ftell () function gives current position of file pointer.

rewind () rewind () function moves file pointer position to the beginning of the file.

getc () getc () function reads character from file.

getch () getch () function reads character from keyboard.

getche () getche () function reads character from keyboard and echoes to o/p screen.

getchar () getchar () function reads character from keyboard.

putc () putc () function writes a character to file.

putchar () putchar () function writes a character to screen.

printf () printf () function writes formatted data to screen.


sprinf () sprinf () function writes formatted output to string.

scanf () scanf () function reads formatted data from keyboard.

sscanf () sscanf () function Reads formatted input from a string.

remove () remove () function deletes a file.

fflush () fflush () function flushes a file.

Error Handling in C
Error handling is the concept where it is conducted to respond to the occurrences of the error during computations of programs,
applications, etc which also includes detection and process of how to resolve these errors. There are different ways of handling errors in
different programming languages. In C programming language there is no support for error handling but instead, it provides methods and
variables that are provided by the C standard library file called error.h which helps to find the errors and return to the function call. In
general, the C language usually returns the function values in either -1 or NULL for error cases.
C language does not provide any direct support for error handling. However a few methods and variables defined in error.h header file can
be used to point out error using the return statement in a function. In C language, a function returns -1 or NULL value in case of any error
and a global variable errno is set with the error code. So the return value can be used to check error while programming.
Global variable Errno
In C programming language, this is a variable where it is known as errno and is assigned a specific number or code that is used within the
program to detect the type of error. Such type of error is declared in the header file known as error.h, so there are different error numbers
for different types of errors and some of them are listed below:

Error number Error description

1 Operation not permitted

2 No such file or directory

3 No such process

4 Interrupted system calls

5 I/O error

6 No such device or address

Now let us see an example, to see what error value will be displayed if the file does not exists.
Below is the example are as follows:
Code:
#include <stdio.h>
#include <errno.h>
int main()
{
FILE * f;
f = fopen("article.txt", "r");
printf(" Value of error number as errno: %d\n ", errno);
return 0;
}
Output:
Value of error no as errno:2
In the above program, we are trying to open a file that does not exist, and hence it will give an error
that has been assigned a value and it is errno 2.
2. Perror() and strerror()
There are two different methods or functions in C, which are used to display the error message instead of just
displaying the errno as we did it in the above program. They are as follows:
perror()
This function takes the message to be displayed which also displays the textual representation of errno.
Syntax:
void perror (const char *s)
s: – can be a string or message to be printed before the error message.
strerror()
This function points to the string or message or textual representation of the errno value and this function is
defined in the header file string.h library.
Syntax:
char *strerror( int errornum)
errornum: this contains the error number i.e. errno.
The above two functions can be demonstrated by the below program. Below is the example are as follows:
Code:
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno ;
int main () {
FILE * f;
int errornum;
f = fopen ("article.txt", "rb");
if (f == NULL) {
errornum = errno;
fprintf(stderr, "The Value of errno: %d\n", errno);
perror("Error message that is printed by perror");
fprintf(stderr, "Error message for opening file that does not exist:
%s\n", strerror( errornum ));
} else {
fclose (f);
}
return 0;
}
Output:
The value of errno:2
Error message that’s printed by perror:No such file or directory
Error message for opening file that doesn’t exist : No such file or directory
In the above program, we are trying to open a file that does not exist so to print the customized message for such error we using perror()
and strerror() function which will print the error message along with errno with a customized error message.

Example 2

Time for an Example

#include <stdio.h>

#include <errno.h>
#include <string.h>

int main ()

FILE *fp;

/*

If a file, which does not exists, is opened,

we will get an error

*/

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

printf("Value of errno: %d\n ", errno);

printf("The error message is : %s\n", strerror(errno));

perror("Message from perror");

return 0;

Copy

Value of errno: 2

The error message is: No such file or directory

Message from perror: No such file or directory

We can also use Exit Status constants in the exit() function to inform the calling


function about the error. The two constant values available for use
are EXIT_SUCCESS and EXIT_FAILURE. These are nothing but macros
defined stdlib.h header file.
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

extern int errno;

void main()
{
char *ptr = malloc( 1000000000UL); //requesting to allocate 1gb memory space
if (ptr == NULL) //if memory not available, it will return null
{
puts("malloc failed");
puts(strerror(errno));
exit(EXIT_FAILURE); //exit status failure
}
else
{
free( ptr);
exit(EXIT_SUCCESS); //exit status Success
}
}
Here exit function is used to indicate exit status.EXIT_SUCCESS and EXIT_FAILURE are two macro used to show
exit status. In case of program coming out after a successful operation EXIT_SUCCESS is used to show successful
exit. It is defined as 0. EXIT_Failure is used in case of any failure in the program. It is defined as -1.
Divide by Zero Error
The statement itself defines the error as this is displayed or occurred when the divisor is zero before a division command so this leads to
dividing by zero error.
There are some situation where nothing can be done to handle the error. In C language one such situation is division by
zero. All you can do is avoid doing this, becasue if you do so, C language is not able to understand what happened, and
gives a runtime error.
Best way to avoid this is, to check the value of the divisor before using it in the division operations. You can
use if condition, and if it is found to be zero, just display a message and return from the function.

DETECT END OF FILE


In C/C++, getc() returns EOF when end of file is reached. getc() also returns EOF when it fails. So, only comparing the value returned by
getc() with EOF is not sufficient to check for actual end of file. To solve this problem, C provides feof() which returns non-zero value only if
end of file has reached, otherwise it returns 0.
For example, consider the following C program to print contents of file test.txt on screen. In the program, returned value of
getc() is compared with EOF first, then there is another check using feof(). By putting this check, we make sure that the
program prints “End of file reached” only if end of file is reached. And if getc() returns EOF due to any other reason, then
the program prints “Something went wrong”

#include <stdio.h>
int main()
{
  FILE *fp = fopen("test.txt", "r");
  int ch = getc(fp);
  while (ch != EOF) 
  {
    /* display contents of file on screen */ 
    putchar(ch); 
    ch = getc(fp);
  }
  if (feof(fp))
     printf("\n End of file reached.");
  else 
     printf("\n Something went wrong.");
  fclose(fp);   
  getchar();
  return 0;
}
getc()
It reads a single character from the input and return an integer value. If it fails, it returns EOF.
Here is the syntax of getc() in C language,
int getc(FILE *stream);
Here is an example of getc() in C language,
Let’s say we have “new.txt” file with the following content −
This is demo!
This is demo!
Now, let us see the example.
Example
#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   fclose(f);
   getchar();
   return 0;
}
Output
This is demo!
This is demo!

feof()
The function feof() is used to check the end of file after EOF. It tests the end of file indicator. It returns non-zero value if successful otherwise, zero.
Here is the syntax of feof() in C language,
int feof(FILE *stream)
Here is an example of feof() in C language,
Let’s say we have “new.txt” file with the following content −
This is demo!
This is demo!
Now, let us see the example.
Example
#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   if (feof(f))
   printf("\n Reached to the end of file.");
   else
   printf("\n Failure.");
   fclose(f);
   getchar();
   return 0;
}
Output
This is demo!
This is demo!
Reached to the end of file.
In the above program, In the above program, file is opened by using fopen(). When integer variable c is not equal to EOF, it will read the file. The fu
feof() is checking again that pointer has reached to the end of file or not.

Random Access To File


There is no need to read each record sequentially, if we want to access a particular record.C supports
these functions for random access file processing.
fseek()
ftell()
rewind()
fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are skipped backward (if
negative) or forward( if positive) from the current position.This is attached with L because this is a long
integer.
Pointer position:
This sets the pointer position in the file.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file

Ex:
1) fseek( p,10L,0)

0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10
bytes from the beginning of the file.

2)fseek( p,5L,1)

1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes
forward from the current position.

3)fseek(p,-5L,1)

From this statement pointer position is skipped 5 bytes backward from the current position.

ftell()
This function returns the value of the current pointer position in the file.The value is count from the
beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.

Example program for fseek():


Write a program to read last ‘n’ characters of the file using appropriate file functions(Here we need
fseek() and fgetc()).
01 #include<stdio.h>
02 #include<conio.h>
03 void main()
04 {
05      FILE *fp;
06      char ch;

07      clrscr();
08      fp=fopen("file1.c", "r");
09      if(fp==NULL)
10       printf("file cannot be opened");
11      else
12      {
13         printf("Enter value of n  to read last ‘n’ characters");
14         scanf("%d",&n);

15         fseek(fp,-n,2);
16         while((ch=fgetc(fp))!=EOF)
17         {
18              printf("%c\t",ch);
19           }
20       }
21   fclose(fp);
22   getch();
23 }

OUTPUT: It depends on the content in the file.

Command line argument

Command line argument is a parameter supplied to the program


when it is invoked. Command line argument is an important
concept in C programming. It is mostly used when you need to
control your program from outside. Command line arguments are
passed to the main() method.
Syntax:
int main(int argc, char *argv[])
Here argc counts the number of arguments on the command line
and argv[ ] is a pointer array which holds pointers of type char which
points to the arguments passed to the program.
Example for Command Line Argument
#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[])


{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
Output:
The arguments supplied are:
Bushra
If not, argument list is empty.
PREPROCESSOR COMMANDS
In C programming language, preprocessor directive is a step performed before the actual source code compilation. It is
not part of the compilation. Preprocessor directives in C programming language are used to define and replace tokens in
the text and also used to insert the contents of other files into the source file.
When we try to compile a program, preprocessor commands are executed first and then the program gets compiled.
Every preprocessor command begins with # symbol. We can also create preprocessor commands with parameters.

Preprocessor directives, such as #define and #ifdef, are typically used to make source programs easy to change and easy to
compile in different execution environments. Directives in the source file tell the preprocessor to take specific actions. For
example, the preprocessor can replace tokens in the text, insert the contents of other files into the source file, or suppress
compilation of part of the file by removing sections of text. Preprocessor lines are recognized and carried out before macro
expansion. Therefore, if a macro expands into something that looks like a preprocessor command, it isn't recognized by the
preprocessor.

Preprocessor statements use the same character set as source file statements, with the exception that escape sequences aren't
supported. The character set used in preprocessor statements is the same as the execution character set. The preprocessor also
recognizes negative character values.

 a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual
compilation. t must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column.

Sr.No. Directive & Description

1 #define
Substitutes a preprocessor macro.

2 #include
Inserts a particular header from another file.

3 #undef
Undefines a preprocessor macro.

4 #ifdef
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not defined.

6 #if
Tests if a compile time condition is true.

7 #else
The alternative for #if.

8 #elif
#else and #if in one statement.

9 #endif
Ends preprocessor conditional.

10 #error
Prints error message on stderr.

11 #pragma
Issues special commands to the compiler, using a standardized method.

Preprocessors Examples----- https://www.tutorialspoint.com/cprogramming/c_preprocessors.htm


#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text
to the current source file. The next line tells CPP to get myheader.h from the local
directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42

It tells the CPP to undefine existing FILE_SIZE and define it as 42.

FILES PROGRAMS
// program to file copy
#include <stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen("test.txt","r");
fp2=fopen("demo.txt","w");
c = fgetc(fp1);
while (c != EOF)
{
c=toupper(c);
fputc(c, fp2);
c = fgetc(fp1);
} //copying completed
fclose(fp1);
fclose(fp2);
fp2=fopen("demo.txt","r") ;
while ((c=fgetc(fp2)) != EOF)
{
printf("%c",c);
}
return 0;
}

DISPLAY CONTENTS OF FILE

#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr;
char filename[100], c;
printf("Enter the filename to open \n");
scanf("%s", filename);
// Open file
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}

// Read contents from file


c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;
}

Output:
Enter the filename to open
a.txt
chocolates

OCCURRENCE OF FILES---FILE NAME AND CHAR NAME SUPPLIED AT COMMAND LINE ARGUMENTS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[]){
FILE *finp;
int i;
char l,c;
int count=0;
if((finp=fopen(argv[2], "r")) == NULL)
{
printf("Error Reading input!\n");
}
c=argv[1][0];
printf("\nfile name is: %s",argv[2]);
printf("\ncharcater is: %s",argv[1]);
while((l = fgetc(finp))!=EOF)
{
if(l==c)
{
count++;
}
}
printf("\nThe %c charcater occured %d times",c,count);
fclose(finp);
}

FILE NAME CREATED IS OCCURRENCE ---THAT HAS


THIS IS BUSHRA
Output:
file name is: occurence
charcater is: S
The S charcater occured 3 times

REVERSE N CHAR OF FILES


#include <stdio.h>
int main(int argc,char *argv[])
{
int n,i,l;
char c;
FILE *fp1,*fp2;
printf("given file name and n value at command line");
fp1=fopen(argv[1],"r");
fp2=fopen("test.txt","w+");
n=atoi(argv[2]);
fseek(fp1,n-1,0);//changing position from beg to nth position
l=ftell(fp1);
printf("\n position is %d",l);
for(i=0;i<n;i++)
{
c=fgetc(fp1);
fputc(c,fp2);
//printf(" \nc is %c",c);
fseek(fp1,-2,1);
//l=ftell(fp1);
}
fseek(fp1,n,0);
while((c=fgetc(fp1))!=EOF)
{
fputc(c,fp2);
}
//COPYING BY REVERSING FIRST N CHARACTERS IS COMPLETED.
rewind(fp2);
printf("\nThe resultant file is\n");
while((c=fgetc(fp2))!=EOF)
{
printf("%c",c);
}
return 0;
}
two FILES CREATED—demo.txt,test.txt
demo.txt has SINGAPORE
test.txt automatically changes to the reversed value given by the digit in the command line arguments along with the
demo.txt file
if suppose ive given this in CLA as demo.txt 5 then the output is shown below

OUTPUT:
given file name and n value at command line
position is 4
The resultant file is
AGNISPORE

You might also like