File Handling
File Handling
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
function purpose
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:
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);
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.
fgets () fgets () function reads string from a file, one line at a time.
fputchar () fputchar () function writes a character onto the output screen from keyboard input.
SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.
rewind () rewind () function moves file pointer position to the beginning of the file.
getche () getche () function reads character from keyboard and echoes to o/p screen.
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:
3 No such process
5 I/O error
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
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
FILE *fp;
/*
*/
fp = fopen("IWillReturnError.txt", "r");
return 0;
Copy
Value of errno: 2
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.
#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.
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.
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 }
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.
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.
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;
}
#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);
}
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);
}
OUTPUT:
given file name and n value at command line
position is 4
The resultant file is
AGNISPORE