C Unit 5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

I B.

SC - 2 Semester (‘C’ Language) UNIT- 5


Unit – V
Files:
Introduction to Files – Using Files in C – Reading Data from Files – Writing Data from Files –
Detecting the End-of-file – Error Handling during File Operations – Accepting Command Line Arguments –
Functions for Selecting a Record Randomly - Remove() – Renaming a File – Creating a Temporary File.

File Handling in C
Definition of a File
File is a set of records that can be accessed through the set of library functions.
Stream
Stream means reading and writing of data. The streams are designed to allow the user to access
the files efficiently. A stream is a file or physical device like keyboard, printer and monitor. The FILE
object uses these devices.
The FILE object contains all the information about stream like current position, pointer to any buffer,
error and EOF (end of file).
File Types
There are two types of files.
_ Sequential Access File
_ Random Access File
Sequential Access File
In this file the records are kept sequentially. If we want to read the last record of the file we need
to read all the records before that record. It takes more time. For example if we desired to access the
10th record then the first 9 records should be read sequentially for reaching to the 10th record.
Random Access File
In this type data can be read and modified randomly. In this type if we want to read the last
record of the file, we can read it directly. It takes less time as compared to sequential file.
File operations:
There are three steps for the file operation in C.
 _ Opening a File.
 _ Reading or Writing file.
 _ Closing file.
To perform the above operations on a file we have number of file handling function in <stdio.h>
header file. These are explained below.
File Handling Functions
The C programming language supports many more file handling functions that are available in
standard library. These functions are listed in the below table.

Aditya Degree College, GWK - By Mohana Roopa 1


I B.SC - 2 Semester (‘C’ Language) UNIT- 5

Opening a File
A file has to b opened before beginning of read and write operations. Opening of a file creates a
link between the operating system and the file functions.
When we open a file we must also specify what we wish to do with it i.e. Read from the file,
Write to the file, or both.
Because we may use a number of different files in our program, we must specify when reading
or writing which file we wish to use. This is accomplished by using a variable called a file pointer.
Every file we open has its own file pointer variable. When we wish to write to a file we specify
the file by using its file pointer variable.
We can declare these file pointer variables as follows:
FILE *fp1, *fp2, *fp3;
The variables fp1, fp2, fp3 are file pointers.
The file <stdio.h> contains declarations for the Standard I/O library and should always be
included at the very beginning of C programs using files.
The only one function to open a file is fopen().
Syntax for fopen()
fp1=fopen(“D:/abc.txt”,”r”);
The above statement opens a file called abc.txt for reading and associates the file pointer fp
with the file.
Closing a file:
The file that is opened from the fopen() should be closed after the work is over i.e., we need to
close the file after reading and writing operations are over.
Example:
fclose(fp);
this statement closes the file associated with the file pointer fp.
Text Modes
1. w (write)
This mode opens a new file on disk for writtng. If the file already exists, it will be overridden
without confirmation.
Syntax:
fp=fopen(“D:/abc.txt”,”w”);
Here, abc.txt is the file name and “w” is the mode.
2. r (read)
This mode opens a pre-existing file for reading. If the file doesn’t exist, then compiler returns
NULL to the file pointer.
Syntax:
fp=fopen(“D:/abc.txt”,”r”);
if(fp==NULL)

Aditya Degree College, GWK - By Mohana Roopa 2


I B.SC - 2 Semester (‘C’ Language) UNIT- 5
printf(“File does not exist”);
3. a (append)
This mode opens a pre-existing file for appending data. If the file does not exist then new file is
opened i.e., if the file does not exist then the mode of “a” is same as “w”.
Syntax:
fp=fopen(“D:/abc.txt”,”a”);
4. w+ ( Write + Read)
It searches for the file, if found its contents are destroyed. If the file does not found a new file is
created. Returns NULL if fails to open the file. In this mode file can be written and read.
Syntax:
fp=fopen(“D:/abc.txt”,”w+”);
The following program illustrates the concept of opening a file in read mode*/

/* file.c: Display contents of a file on screen */


#include <stdio.h>
void main()
{
FILE *fp;
int c ;
fp=fopen("file.c","r");
if(fp==NULL)
printf("File not found");
else
{
printf("\n The content of the file is......\n");
c = getc(fp);
while (c!=EOF)
{
putchar(c);
c=getc(fp);

}
fclose(fp);
getch();
}

Reading data from file : Input functions used are ( Input operations on files)
a) getc(): It is used to read characters from file that has been opened for read operation.
Syntax: c=getc (file pointer)
This statement reads a character from file pointed to by file pointer and assign to c. It returns an
end-of-file marker EOF, when end of file has been reached.
b) fscanf(): This function is similar to that of scanf function except that it works on files.
Syntax: fscanf (fp, ”control string”, list);
Example fscanf(f1,”%s%d”,str,&num);
The above statement reads string type data and integer type data from file.
c) getw(); This function reads an integer from file.
Syntax: getw (file pointer);
d)fgets(): This function reads a string from a file pointed by a file pointer. It also copies the string to a
memory location referred by an array.
Syntax: fgets(string,no of bytes,filepointer);

Aditya Degree College, GWK - By Mohana Roopa 3


I B.SC - 2 Semester (‘C’ Language) UNIT- 5
e)fread(): This function is used for reading an entire structure block from a given file.
Syntax: fread(&struct_name,sizeof(struct_name),1,filepointer);

Writing data to a file:


To write into a file, following C functions are used
a. putc():This function writes a character to a file that has been opened in write mode.
Syntax: putc(c,fp);
This statement writes the character contained in character variable c into a file whose pointer is fp.
b.fprintf():This function performs function, similar to that of printf.
Syntax: fprintf(f1,”%s,%d”,str,num);
c. putw():It writes an integer to a file.
Syntax: putw (variable, fp);
d. fputs(): This function writes a string into a file pointed by a file pointer.
Syntax: fputs(string, filepointer);
e. fwrite(): This function is used for writing an entire block structure to a given file. Syntax:
fwrite(&struct_name, sizeof(struct_name),1,filepointer);
Copy one file to another file:

#include <stdio.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
Aditya Degree College, GWK - By Mohana Roopa 4
I B.SC - 2 Semester (‘C’ Language) UNIT- 5
return 0;
}

Handling errors during I/O operations


While performing read or write operations sometimes we do not get the result successfully. The
reason may be that the attempt of reading or writing the operation may not be correct.
It is possible that an error may occur during I/O operations on a file.
Typical error situations include:
1. Trying to read beyond the end of file mark.
2. Device overflow
3. Trying to use a file that has not been opened
4. Trying to perform an operation on a file, when the file is opened for another type of
operations
5. Opening a file with an invalid filename
6. Attempting to write a write protected file
The C-Language provides the following standard library functions to handle these type of errors
during I/O operations.
ferror()
It is used to detect any error that might occur during read/write operation on a file. It returns ‘0’
when the attempt is successful otherwise non-zero in case of failure.
perror()
It is a standard library function which prints the error messages specified by the compiler.
The following program illustrates the above two functions…..
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("abc.txt","w");
while(!feof(fp))
{
ch=fgetc(fp);
if(ferror(fp))
{
perror("Permission Denied");
getch();
exit(1);
}
else
{
printf("%c",ch);
}
}
fclose(fp);
getch();
}

Command Line Arguments in C:


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.

Aditya Degree College, GWK - By Mohana Roopa 5


I B.SC - 2 Semester (‘C’ Language) UNIT- 5
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:
#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;
}

Remember that argv[0] holds the name of the program and argv[1] points to the first command
line argument and argv[n] gives the last argument. If no argument is supplied, argc will be 1.

Aditya Degree College, GWK - By Mohana Roopa 6

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy