C FILE HANDLING
- Seema Sharma
WHAT IS FILE
A collection of data or information that are stored
on a computer known as file.
Data files
Can be created, updated, and processed by C programs
Are used for permanent storage of large amounts of
data
WHY FILES ARE NEEDED?
When a program is terminated, the entire data is
lost. Storing in a file will preserve your data even if
the program terminates.
If you have to enter a large number of data, it will
take a lot of time to enter them all.
However, if you have a file containing all the data,
you can easily access the contents of the file using
a few commands in C.
You can easily move your data from one computer
to another without any changes.
TYPES OF FILES
When dealing with files, there are two types of files
you should know about:
Text files
Binary files
TEXT FILES
Text files are the normal .txt files. You can easily
create text files using any simple text editors such
as Notepad.
When you open those files, you'll see all the
contents within the file as plain text. You can easily
edit or delete the contents.
BINARY FILES
mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in
the binary form (0's and 1's).
Binary files
FILE OPERATIONS
Major operations on files, either text or binary are as
follows
Creation of a new file (fopen with
attributes as “a” or “a+” or “w” or “w++”)
Opening an existing file (fopen)
Reading from file (fscanf or fgetc)
Writing to a file (fprintf or fputs)
Moving to a specific location in a file
(fseek, rewind)
Closing a file (fclose)
CREATION OF A NEW FILE
We can use one of the following modes in the fopen() function
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb,wb,ab,rb+,wb+,ab+ for Binary files
FILE NAME AND FILE POINTER
A file is identified by its name.
This name is divided into two parts
File Name -:-It consists of alphabets and digits Special
characters are also supported, but it depends on the
operating system we use.
Extension :- It describes the file type
Before opening a file, we need to declare a file
pointer.
A file pointer is a pointer variable of type FILE,
which is defined in the “stdio.h” header file
CREATE A FILE IN
Declare a FILE type pointer variable to store
reference of file, say
FILE * fPtr = NULL;.
Create or open file using fopen() function.
fopen() function is used to open a file in different mode.
You can open a file in basic three different mode r(read),
w(write) and a(append) mode. We will use w file mode
to create a file
fopen("file-name", "read-mode");
FOPEN
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
EXAMPLE
#include <stdio.h>
int main()
{
FILE *fp; fp = fopen ("data.
txt", "w");
}
File is created in the same folder where
you have saved your code.
EXAMPLE
You can specify the path where you want to create your
file
#include <stdio.h>
int main()
{
FILE *fp; fp = fopen ("D://data.txt",
"w");
}
CLOSE A FILE
One should always close a file whenever the operations
on file are over
The syntax of fclose is as follows,
fclose (file_pointer);
Example:
FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);
WRITING TO A FILE
In C, when you write to a file, newline characters '\n'
must be explicitly added.
The stdio library offers the necessary functions to
write to a file:
fputc(char, file_pointer): It writes a character to the file
pointed to by file_pointer.
fputs(str, file_pointer): It writes a string to the file
pointed to by file_pointer.
fprintf(file_pointer, str, variable_lists): It prints a string to
the file pointed to by file_pointer. The string can
optionally include format specifiers and a list of
variables variable_lists.
FPUTC() FUNCTION:
#include <stdio.h>
int main()
{
int i;
FILE * fptr;
char fn[50];
char str[] = "JECRC UNIVERSITY\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing mode"
for (i = 0; str[i] != '\n'; i++)
{
/* write to file using fputc() function */
fputc(str[i], fptr); output
}
fclose(fptr); return 0;
} JECRC UNIVERSITY
FPUTS () FUNCTION:
#include <stdio.h>
int main()
{
FILE * fp;
fp = fopen("fputs_test.txt", "w+");
fputs("JECRC UNIVERSITY,", fp);
fputs(“JAIPUR\n", fp);
fputs(“RAJASTHAN", fp); fclose(fp);
return (0);
}
OUT PUT
JECRC UNIVERSITY, JAIPUR
RAJASTHAN
FPRINTF()FUNCTION:
#include <stdio.h>
int main()
{
FILE *fptr;
fptr = fopen("fprintf_test.txt", "w");
// "w" defines "writing mode" /* write to file */
fprintf(fptr, "Learning C with JU");
fclose(fptr);
return 0; }
OUTPUT:
Learning C with JU
READING DATA FROM A FILE
fgetc(file_pointer):
It returns the next character from the file pointed to by the file
pointer. When the end of the file has been reached, the EOF is
sent back.
fgets(buffer, n, file_pointer):
It reads n-1 characters from the file and stores the string in a
buffer in which the NULL character '\0' is appended as the
last character.
fscanf(file_pointer, conversion_specifiers, variable_adresses):
It is used to parse and analyze data.
It reads characters from the file and assigns the input to a list
of variable pointers variable_adresses using conversion
specifiers.
Keep in mind that as with scanf, fscanf stops reading a string
when space or newline is encountered.
#include <stdio.h>
int main()
{
FGETC ()
FILE * file_pointer;
char buffer[30], c;
file_pointer = fopen("fprintf_test.txt", "r");
printf("----read a line----\n");
fgets(buffer, 50, file_pointer);
printf("%s\n", buffer);
printf("----read and parse data----\n");
file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer
char str1[10], str2[2], str3[20], str4[2];
Output
fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4);
printf("Read String1 |%s|\n", str1);
printf("Read String2 |%s|\n", str2);
-----read a line----
printf("Read String3 |%s|\n", str3);
Learning C with JU
printf("Read String4 |%s|\n", str4); ----read and parse data---- Read
printf("----read the entire file----\n"); String1 |Learning|
file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer Read String2 |C|
while ((c = getc(file_pointer)) != EOF) Read String3 |with|
printf("%c", c); Read String4 |JU|
fclose(file_pointer); ----read the entire file---- Learning C
return 0; } with Guru99
READ AND WRITE WITH GETC AND PUTC
#include <stdio.h>
int main()
{
FILE * fp;
char c; OUTPUT
printf("File Handling\n");
//open a file JU2020
fp = fopen("demo.txt", "w"); //writing operation ^Z
while ((c = getchar()) != EOF) Data entered
{ JU2020
putc(c, fp); } //close file
fclose(fp);
printf("Data Entered:\n");
//reading
fp = fopen("demo.txt", "r");
while ((c = getc(fp)) != EOF)
{ printf("%c", c);
}
fclose(fp);
return 0;
}
OTHER EXAMPLES
#include <stdio.h>
#include <stdlib.h>
int main()
{ int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL)
{
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
FSEEK()
Syntax of fseek()
int fseek(FILE *pointer, long int offset, int position)
pointer: pointer to a FILE object that identifies the stream.
offset: number of bytes to offset from position
position: position from where offset is added.
returns: zero if successful, or else it returns a non-zero value
SEEK_END : It denotes end of the file.
SEEK_SET : It denotes starting of the file.
SEEK_CUR : It denotes file pointer’s current position.
FSEEK()
// C Program to demonstrate the use of fseek()
#include <stdio.h>
int main()
{
FILE *fp; Output:
fp = fopen("test.txt", "r");
81
// Moving pointer to end
fseek(fp, 0, SEEK_END);
// Printing position of pointer
printf("%ld", ftell(fp));
return 0;
}
THANK YOU
ANY QUESTION ?