FILES-C

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

UNIT-V

A file is a collection of data or information stored in secondary storage devices such as hard
disk, floppy disk devices.

Normally, a program input and output values through the variables which are created in
primary memory. So the values given by a user are stored temporarily.
Once the program execution completes, the values are automatically removed.
A file is created in the secondary memory device such as disk or tape. After creating a file,
we can modify or delete data present in the file as and when needed.

To manipulate files in ‘C’ language, we must use FILE data type. It is structure data type that
is used to create file buffer area. The general format is as follows.
Syntax: FILE *fp;
Here, FILE is the name of data type and ‘fp’ is file pointer which will contain all the
information about the file.

USING FILES IN C
To use files in C, we must follow the steps given below:
1. Declare a file pointer variable
2. Open the file
3. Process the file
4. Close the file
Declare a file pointer variable:
There can be a number of files on the disk. To access a particular file, you must specify the
name of the file that has to be used. This is accomplished by using a file pointer variable that
points to a structure FILE.
Syntax: FILE *file_pointer_name;
Example: FILE *fp
Above, fp is declared as a file pointer.
Opening the file:
A file should be opened before it is used in the program. The fopen() function is used to open
a file. If the file open operation is success, this function returns a FILE pointer otherwise it
returns NULL.
Syntax: fp=fopen(“file_name”,”mode”)
Ex: fp=fopen(“first”,”r”);
1. fp is a pointer to a FILE.
2. File_name is the name of the file to be opened.
3. Mode determines how the file may be accessed.
Mode Meaning
“r” Opens text file for reading
“w” Opens text file for writing
“a” Opens text file in append mode
“r+” Opens text file for reading and writing
“w+” Opens text file for writing and reading
“rb” Opens binary file for reading
“wb” Open a binary file for writing
“ab” Append to a binary file
“r+b/rb+” Open a binary file for read/write
“w+b/wb+” Create a binary file for read/write
“a+b/ab+” Append a binary file for read/write

1
UNIT-V

Closing a File:
A file must be closed when no input/output is to be performed on it. The function fclose() is
used to close the file.
Syntax: fclose(file_pointer)
Example: fclose(fp) where fp is a file pointer that holds the opened file.

EXPLAIN I/O OPERATIONS ON FILES IN C? OR EXPLAIN READ DATA FROM


FILES AND WRITING DATA TO FILES?
The following functions are used to manipulate data in the files
Input functions:
fgetc(), fgets(), fscanf()
fgetc():
This function is used to read a single character from the file and stores it in a variable.
Syntax: variable = getc(fp);
Here ‘variable’ is a character type variable and ‘fp’ is file pointer
fgets():
This function is used to read the specified number of characters from the file and stores it in a
variable.
Syntax: fgets(str, n, fp);
Here, ‘str’ is a string variable. ‘n’ is number of characters to be read from the file ’fp’ is file
pointer. It means, this function reads ‘n’ characters from the file ‘fp’ and stores it in the
variable ‘str’.
Ex: fgets(nm, 10, fp);
fscanf():
This function is used to read data items from the file and stores them into variables. It read
values based on formatting characters specified. This function returns an integer if it is
success otherwise it returns zero.
Syntax: fscanf(fp, format-string, variable-list);
Here ‘fp’ is file pointer. The ‘format-string’ contains formatting characters. The ‘variable-
list’ contains one or more variables.
Ex fscanf(fp, “%d %s %f” , &rno, snm, &avg);

Output functions:
fputc(), fputs(), fprintf(), etc.,

fputc() functions:
This function is used to store a single character into file. The general format is as follows:
Syntax : fputc(ch, fp);
Here, ‘ch’ is a character variable or constant and ‘fp’ is file pointer.
fputs() function:
This function is used to store a string into the file.
Syntax : fputs(string, fp);
Here , ‘string’ is a string constant or variable. ‘fp’ is file pointer.
Ex : fputs(nm, fp);
fprintf():
This function is used to store data items into the file. It writes values based on formatting
characters specified. The general format is as follows:

2
UNIT-V

Syntax : fprintf(fp, format-string, variable-list);


Here ‘fp’ is a file pointer. The format-string contains formatting characters. The ‘variable-
list’ contains one or more variables separated by commas.

STREAMS IN C
Stream is nothing but the sequence of bytes of data.
A sequence of bytes flowing into program is called input stream.
A sequence of bytes flowing out of the program is called output stream.
Predefined streams:
Standard input (stdin):
Keyboard is a standard input device. Standard input is data going into a program. The
program requests data transfer by use of read operation.
Standard output (stdout)
Screen (monitor) is standard output device. Standard output is data going out from a program.
The program sends data to output device by using write operation.
Standard error (stderr)
Standard error is basically an output stream used by programs to report error messages.

TYPES OF FILES
The types of files used can be broadly classified into 2 categories.
1. Text File
2. Binary File
Text File:- A text file stores textual information like alphabets, numbers, special symbols,
etc. In actuality, the ASCII code of textual characters stored in the text files. But, since data is
stored in a storage device in binary format, the text file contents are first converted in the
binary form before actually being stored in the storage device. A text file can store different
character sets such as:
1. Upper case English alphabets
2. Lower case English alphabets
3. Numeric characters
4. Punctuation characters
5. Special characters
Binary file:- A binary file stores the information in the binary form, i.e., in the same format
as it is stored in the memory. Thus, the use of binary file eliminates the need of data
conversion from text to binary format for storage purpose. However, on the main drawbacks
of binary file is that the data stored in a binary file is not in human understandable form. Any
file which stores the data in the form of bytes, i.e., 8-bit representation is known as binary
file.

COMMAND-LINE ARGUMENTS
C facilitates its programmers to pass command arguments. Command line arguments are
given after the name of a program in command line operating system like DOS or LINUX,
and are passed in to the program from the operating system.
The main() function can accept two arguments.
1. The first argument is an integer value that specifies number of command line
arguments. (argc)

3
UNIT-V

2. The second argument is a full list of all of the command line argument(argv)
Syntax: main(int argc, char *argv[])
The variable ‘argc’ is an argument counter that counts the number of arguments on the
command line. The ‘argv’ is an argument vector and represents an array of character pointers
that points to the ‘Command Line Arguments”.
Example:
#include<stdio.h>
main(int argc, char *argv[])
{
int i;
printf("number of arguments %d\n", argc);
for(i=0;i<argc; i++)
printf("argv[%d]=%s\n" ,i,argv[i]);
}

ERROR HANDLING
An error may occur while reading data from or writing data to a file. An error may rise
 When trying to read a file beyond EOF indicator.
 When trying to read a file that does not exist
 When trying to use a file that has not been opened.
 When trying to use a file in an inappropriate mode, i.e., writing data to a file that
has been opened for reading.
 When writing to a file that is write – protected.

ferror():
It is used to check for errors in the stream.
Syntax: int ferror(FILE *stream)
The ferror() function checks for any errors in the stream. It returns value 0 if no errors
have occurred and a non-zero value if there is an error.
clearerr ():
It is used to clear the end of file and error indicators for the stream.
Syntax: void clearer(FILE *stream);
The clearer() clears the error for the stream pointed to by stream. The function is used
because error indicators are not automatically cleared.
perror()
The function perror() stands for print error. The prototype of perror() can be given as
Syntax: void perror(char *msg);

RANDOM ACCESS TO FILES


There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.

1. fseek()
2. ftell()
3. rewind()
fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
file pointer—it is the pointer which points to the file.
4
UNIT-V

displacement ---- It is positive or negative. This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position. This is attached with
L because this is a long integer.
Pointer position:
This sets the pointer position in the file.

Value pointer position


0 Beginning of file.
1 Current position
2 End of file
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.

Program
#include<stdio.h>
main()
{
FILE *f;
char ch;
int n;
f=fopen("cnu.txt","r");
if(f==NULL)
printf(" cannot be opened");
else
{
printf(" enter n value");
scanf("%d",&n);
fseek(f,-n,2);
while((ch=fgetc(f))!=EOF)

5
UNIT-V

{
printf("%c",ch);
}
fclose(f);
}
}
Write program to create student data using files?
#include<stdio.h>
main()
{
FILE *fp;
char name[20];
int sno,s1,s2,s3,tot,i;
float avg;
clrscr();
fp=fopen("mscs.txt","w");
printf("Enter the details of three subjects \n");
printf("no\tname\ts1\ts2\ts3\n");
for(i=0;i<3;i++)
{
scanf("%d%s%d%d%d",&sno,name,&s1,&s2,&s3);
fprintf(fp,"%d\t%s\t%d\t%d\t%d\n",sno,name,s1,s2,s3);
}
fclose(fp);
fp=fopen("mscs.txt","r");
printf("\n\n total and average marks of student:\n");
printf("no \t name \t s1 \t s2 \t s3 \t tot \t avg \n");
for(i=0;i<3;i++)
{
fscanf(fp,"%d%s%d%d%d",&sno,name,&s1,&s2,&s3);
tot=s1+s2+s3;
avg=tot/3.0;
fprintf(stdout,"%d\t%s\t%d\t%d\t%d\t%d\t%f\n",sno,name,s1,s2,s3,tot,avg);
}
fclose(fp);
getch();
}

You might also like