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

FILE Handling

Uploaded by

Nandakrishna J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

FILE Handling

Uploaded by

Nandakrishna J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

FILE Handling

Necessity of File Handling

• Reusability: The data stored in the file can be accessed, updated, and
deleted anywhere and anytime providing high reusability.
• Portability: Without losing any data, files can be transferred to another in
the computer system. The risk of flawed coding is minimized with this
feature.
• Efficient: A large amount of input may be required for some programs. File
handling allows you to easily access a part of a file using few instructions
which saves a lot of time and reduces the chance of errors.
• Storage Capacity: Files allow you to store a large amount of data without
having to worry about storing everything simultaneously in a program.
File handling in C enables us to create, update, read, and delete the files
stored on the local file system through our C program. The following
operations can be performed on a file.

•Creation of the new file


•Opening an existing file
•Reading from the file
•Writing to the file
•Deleting the file
Note: The write mode creates an empty file for writing. If a file with the same name
already exists, its content is erased and the file is considered as a new empty file.
Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used
to open a file. The syntax:

1.FILE *fopen( const char * filename, const char * mode );

This function returns a FILE pointer. Otherwise, NULL is returned

Eg.
FILE * fp;
fp = fopen ("file.txt", "w");
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.
It returns the character written on success otherwise EOF if there is an error.
int fputc( int c, FILE *fp );

•fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer. It


returns a non-negative value on success, otherwise EOF is returned in case of any
error.
int fputs( const char *s, FILE *fp );

•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.
Reading data from a File
There are three different functions dedicated to 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>
void main()
{
FILE *fptr;
int id,i;
char name[30];
float salary; fclose(fptr);
fptr = fopen("emp.txt", "w fptr=fopen("emp.txt","r");
for(i=0;i<3;i++) while(fscanf(fptr,"%d",&id)!=EOF)
{ {
printf("Enter the id\n"); fscanf(fptr,"%s%f",name,&salary);
scanf("%d", &id);
fprintf(fptr, "%d\t", id); printf("\n%d\t%s\t%f",id,name,salary) ;
printf("Enter the name \n"); }
scanf("%s", name); fclose(fptr);
fprintf(fptr, "%s\t\t", name); }
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "%.2f\n", salary);
}
Cursor Positioning Functions in Files
C programming language provides various pre-defined
methods to set the cursor position in files. The following
are the methods available in c, to position cursor in a file
.
1.ftell()
2.rewind()
3.fseek()
ftell( *file_pointer ) - This function returns the current position of the cursor in the file.

#include<stdio.h>
#include<conio.h>
int main()
{ FILE *fp;
int position;
Output
clrscr();
fp = fopen ("file.txt", "r"); 05
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0; }
rewind( *file_pointer ) - This function is used reset the cursor position to the beginning of
the file.
#include<stdio.h>
int main()
{ FILE *fp; int position
fp = fopen ("file.txt", "r"); Output
position = ftell(fp);
050
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
position = ftell(fp);
printf("Cursor position = %d", position); f
close(fp);
return 0; }
fseek( *file_pointer, int numberOfCharacters, int fromPosition ) - This function is
used to set the cursor position to the specific position. Using this function we can set
the cursor position from three different position they are as follows.

•from beginning of the file (indicated with 0) or SEEK_SET


•from current cursor position (indicated with 1) or SEEK_CUR
•from ending of the file (indicated with 2) or SEEK_END
Example Program to illustrate fseek() in C.

#include<stdio.h>
int main()
{ FILE *fp; int position; clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
fseek(fp, -5, 2);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp); return 0; }
#include<stdio.h>
PROGRAM TO COPY ONE FILE TO ANOTHER
int main()
{ char ch, fileName1[20], fileName2[20];
FILE *fs, *ft; ch = fgetc(fs);
printf("Enter Source File Name (with while(ch != EOF)
extension): "); gets(fileName1); { fputc(ch, ft);
fs = fopen(fileName1, "r"); ch = fgetc(fs); }
if(fs == NULL) printf("\nFile copied successfully.");
{ printf("\nError in Opening the file, %s", fclose(fs);
fileName1); fclose(ft);
return 0; } return 0; }
printf("Enter Target File Name (with extension):
"); gets(fileName2); ft = fopen(fileName2,
"w");
if(ft == NULL)
{ printf("\nError in Opening the file, %s",
fileName2);
return 0; }
COMMAND LINE ARGUMENTS

It is possible to pass some values from the command line to your C programs
when they are executed.
These values are called command line arguments and many times they are
important for your program especially when you want to control your
program from outside instead of hard coding those values inside the code.

The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer
array which points to each argument passed to the program.
#include <stdio.h>
int main( int argc, char *argv[] )
{ if( argc == 2 )
{ printf("The argument supplied is %s\n",
argv[1]); }
else if( argc > 2 )
{ printf("Too many argument supplied.\n"); }
else
{ printf("One argument expected.\n"); } }

It should be noted that argv[0] holds the name of the program itself and argv[1] is a
pointer to the first command line argument supplied, and *argv[n] is the last argument. If
no arguments are supplied, argc will be one, and if you pass one argument then argc is set
at 2.
#include <stdio.h>

// defining main with arguments


int main(int argc, char* argv[])
{
printf("You have entered %d arguments:\n", argc);

for (int i = 0; i < argc; i++) {


printf("%s\n", argv[i]);
}
return 0;
}

You might also like