0% found this document useful (0 votes)
4 views9 pages

FILES Unit 5

The document provides an overview of file handling in C, including definitions of files, streams, buffers, and types of files. It explains how to open, close, and perform I/O operations on files using various functions, as well as random access file operations and error handling. Additionally, it covers command line arguments and methods for removing and renaming files.

Uploaded by

sudharani.am
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

FILES Unit 5

The document provides an overview of file handling in C, including definitions of files, streams, buffers, and types of files. It explains how to open, close, and perform I/O operations on files using various functions, as well as random access file operations and error handling. Additionally, it covers command line arguments and methods for removing and renaming files.

Uploaded by

sudharani.am
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

FILES

Q) What is file?
A file is a collection of data stored on secondary storage devices such as hard disk.
Files are basically used in real life application involve large amounts of data.

Q) Write about Streams in c?


-A stream is a logical interface to the devices that are connected to the computer.
-Streams are 3 types.
1. Standard input (stdin):-standard input is the stream from which the program receives its data by
using the read operation.
2. Standard output (stdout):-Standard output is the stream where a program writes its output data
by using write operation.
3. Standard error (stderr):-Standard error is basically an output stream used by program to report
error message or diagnostics.

Q) What is Buffer?
 A buffer is nothing but a block of memory that is used for temporary storage of data that has to
read from or written to a file.
 A stream linked to a disk file is created; a buffer is automatically created and associated with
the stream.

Q) What are different Types of files in c.


In C files are classified into
1) ASCII Text files:
 A text file is a stream of characters that can be sequentially processed by a computer in
forward direction.
 A text file usually opened for only one kind of operation (reading, writing, appending) at any
given time.
 Text file only process characters, they can read or write data one character at a time.
 In text file each line contains zero or more characters and ends with one or more characters
that specify end of line.
 Each line contains maximum of 255 characters.
2) Binary files:
 A binary file may contain any type of data, enclosed in binary form for computer storage and
processing purpose.
 A binary file is a collection of bytes.
 Binary files can process sequentially or randomly depending on the needs of application.
 A binary file takes less space to store the data.

Q) Explain how to open and close a file.

1) Declaring a file pointer:


In order to access a particular file, you must specify the name of the file that has to be used.
Syntax:
FILE *fp;
Here fp is the file pointer.

1
2) Opening a file:
A file must be opened before data can be read from or written to it.
In order to open a file we use fopen() function.
Syntax:
fp = fopen( “filename” , “ mode of opening” );
Here fp is a pointer to FILE type and represents a file.
filename is the name of the file being opened (which is remembered by the operating system).
Mode of opening specifies the type of processing that will be done with the file. Mode can be any
one of the following:
mode description

r Opens a text file for reading.

w Opens or create a text file for writing.

a opens a text file in append mode

r+ opens a text file in both reading and writing

w+ Opens or creates a text file in both reading and writing

a+ Opens a text file in both reading and writing.

rb Opens a binary file in reading.

wb Opens or create a binary file in writing.

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

3) Closing a File:-

The file should be closed after reading/writing of a file. Closing a file is performed using
library function fclose().
Syntax: fclose(fp);
Where fp is a pointer to FILE type and represent a file. The file represented by fp is closed.

Q) Explain file I/O functions (OR) explain how to read/write data to a file.
After a file is opened, we can read data stored in a file or write new data onto it depending on the
mode of openings. Standard library supports a good number of functions which can be used for
performing I/O operations.
1) Character Oriented Functions: (fputc() , fgetc()
These are used to read or written characters to a file.

fputc(); fputc() is to write a character onto a file.


2
Syntax: fputc(c,fp);

Where c represents a character and fp, a pointer to FILE, represents a file. The function writes the
content of c onto the file represented by fp.

fgetc(): fgetc() is used to read a character from a file.

Syntax: c=fgetc(fp);

c is a variable of char type and fp is a pointer to FILE type. The function reads a character from the
file denoted by fp and returns the character value, which is collected by the variable c.

Example:

#include <stdio.h>
void main ()
{
FILE *fp;
char ch=’a’;
clrscr();
fp = fopen("file.txt", "w");
fputc(ch, fp);
fclose(fp);
fp = fopen("file.txt","r");
ch = fgetc(fp);
printf("%c", ch);
fclose(fp);
getch();
}

2) String oriented functions (fgets(),fputs()):-


These are used to read strings from a file or write strinf to afile.

fputs(): The fputs() is used to write a string onto a file.

Syntax: fputs(s,fp);

Where s is a string variable and fp is a file pointer to FILE type. The function writes the string
represented by s to the file pointed to by fp.

fgets():The fgets() is used to read a string from the file.

Syntax: fgets(s,size,fp);

s is a string variable, size is an integer value, fp is a pointer of FILE type.


The function reads a string of maximum size-1 characters from the file pointed to by fp and copies it
to the memory area denoted by s.
Example:
#include <stdio.h>
3
int main ()
{
FILE *fp;
char str[30];
clrscr();
fp = fopen("file2.txt", "w");
fputs("This is c programming.", fp);
fclose(fp);
fp = fopen("file2.txt","r");
fgets(str,30,fp);
printf("%s",str);
fclose(fp);
getch();
}

3) Mixed data oriented functions (fprintf(), fscanf()):-

These are used to read or write multiple data items to a file.

fprintf(): fprintf() is used to write multiple data items which may ( or not ) be of different types to a file.

Syntax: fprintf ( pointer, "formatted string", var1,var2....);

Example: fprintf(fp,"%d%s%d",sno,name,fees);

fscanf: fscanf() is used to read mutiple data items which may be of different types from a file.

syntax: fscanf ( pointer, "formatted string", &var1, &var2....);

example: fscanf(fp,"%d%s%d",&sno,&name,&fees);

Example:
#include<stdio.h>
void main()
{
int rno;
char sname[30];
int marks;
FILE *fp;
clrscr();
fp=fopen("student","w");
printf("Enter roll no. register no. name marks\n");
scanf("%d%s%d",&rno,&sname,&marks);
fprintf(fp,"%d\t%s\t%d",rno,sname,marks);
fclose(fp);
fp=fopen("student","r");
fscanf(fp,"%d\t%s\t%d\n",&rno,&sname,&marks);
printf("%d\t%s\t%d\n",rno,sname,marks);
fclose(fp);
4
getch();
}

4) Unformatted record I/O functions (fwrite(),fread()):-

These are used to read or write bocks of data to file.

fwrite():-It is used to write bocks of data(records) to file.

Syntax: fwrite(buufer_address,size,count,file_pointer);

Here buffer_address is the address of the memory area,the contents of which are to be
written to the file denoted by fourth argument file_pointer.
Size specifies the number of bytes of a block.
Count specifies the number of blocks of data written to the file.

fread(): It is used to read blocks of data(records) from files.

Syntax: fread(buffer_address,size,count,file_pointer);

Here buffer_address is the address of the memory area,the contents of which are to be read
to the file denoted by fourth argument file_pointer.
Size specifies the number of bytes of a block.
Count specifies the number of blocks of data read from the file.

Example:
#include <stdio.h>
#include <string.h>
void main()
{
FILE *fp;
char c[] = "this is c programming";
char buffer[100];
clrscr();
fp = fopen("file.txt", "w ");
fwrite(c, strlen(c) + 1, 1, fp);
fclose(fp);
fp=fopen("file.txt","r");
fread(buffer, strlen(c)+1, 1, fp);
printf("%s\n", buffer);
fclose(fp);

getch();
}

Q) Random access files:


Random access means we can move to any part of a file and read or write data from it without having
to read through the entire file. We can access the data stored in the file in two ways.

5
1. Sequentially
2. Randomly

if we want to access the forty fourth record then first forty three record read sequentially to reach forty
four record .In random access data can be accessed and processed directly .There is no need to
read each record sequentially .if we want to access a particular record random access takes less
time than the sequential access.

C standard library provides the following built-in functions to support this:

1) fseek()
2) ftell()
3) rewind()

1) fseek(): The function fseek() repositions the file pointer.

Syntax: fseek (fp, offset, position)

Where fp is a pointer to FILE type representing a file, offset is the number of bytes by which the
file pointer is to be moved relative to the byte number identified by the third parameter position.
The third parameter position can take one of the following three values 0, 1 and 2.

Position Symbolic Constants Meaning


0 SEEK_SET Beginning of file
1 SEEK_CUR Current position of file
2 SEEK_END End of file

2. ftell():
The function ftell() returns the current position of the file pointer.

Syntax: position = ftell (fp);

Where fp is a pointer to FILE type representing a file, the current position of the file pointer of the
file is returned by the function.

3.rewind():
The rewind() repositions the file pointer to the beginning of a file.

Syntax: rewind (fp);

Example : /* write a program to count the number of records in student file*/

#include<stdio.h>
#include<conio.h>
struct std
{
int sno;
char regno[10];
6
char sname[10];
int marks;
};

void main()
{
FILE *fp;
int nor,lb;
clrscr();
fp=fopen("student","r");
fseek(fp,0,SEEK_END);
lb=ftell(fp);
printf("The present position of the file pointer is %d\n",lb);
printf("The size of the student structure is %d\n",sizeof(struct std));
nor=lb/sizeof(struct std);
printf("The no of recors=%d\n",nor);
fclose(fp);
getch();
}

Q) 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>
#include<conio.h>
int main(int argc,char *argv[])
{
FILE *fin,*fout;
char c;
if(argv!=3)
{
printf("invalid agruments\n");
exit(1);
}
fin=fopen(argv[1],"r");
fout=fopen(argv[2],"w");
while(!feof(fin))
{
c=fgetc(fin);
fputc(c,fout);
}
fclose(fin);
fclose(fout);
return 0;
7
}

Q) Error handling during file operations:

C language does not provide direct support for error handling. However few method and variable
defined in error.h header file can be used to point out error using return value of the function call. In
C language, a function return -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.
C language uses the following functions to represent error
 perror() return string pass to it along with the textual represention of current errno value.
 strerror() is defined in string.h library. This method returns a pointer to the string representation
of the current errno value.
Example:
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno ;
int main ()
{
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL)
{
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
}
else {
fclose (pf);
}
return 0;
}

Q) write about Removing and renaming a file.

Removing a file:The remove() function deletes a file from memory.

Syntax: remove(“filename”);

Example:

#include<stdio.h>
void main()
{
remove(“file.txt”);
}

8
Renaming a file: The rename() is used to rename a file. It returns 0 if the rename is success
otherwise it returns a nonzero value.

Syntax: rename(“oldfilename”, ”newfile name”);

#include <stdio.h>

void main ()
{
int success=0;
success=rename(“file.txt”,”newfile.txt”);
if(success!=0)
printf(“file not renamed\n”);
getch();
}

Q) Write about Error handling during life operations.


It is common that an error may be any of the following situations.
1. When trying to read a file beyond EOF indicator
2. When trying to read a file that does not exist.
3. When trying to use a file that has not been opened.
C language does not provide direct support for error handling. However few method and variable
defined in error.h header file can be used to point out error using return value of the function call.
C language uses the following functions to represent error

 perror() return string pass to it along with the textual represention of current errno value.
 strerror() is defined in string.h library. This method returns a pointer to the string representation
of the current errno value.

You might also like