0% found this document useful (0 votes)
5 views30 pages

UNIT 5 C NOTES

The document provides an overview of file processing in C, detailing types of file access (sequential and random), file types (text and binary), and essential functions for file operations such as fopen, fclose, fprintf, and fscanf. It explains the importance of files for data efficiency, reusability, and portability, and outlines the general steps for processing files. Additionally, it covers binary file operations and functions like fwrite and fread for handling binary data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views30 pages

UNIT 5 C NOTES

The document provides an overview of file processing in C, detailing types of file access (sequential and random), file types (text and binary), and essential functions for file operations such as fopen, fclose, fprintf, and fscanf. It explains the importance of files for data efficiency, reusability, and portability, and outlines the general steps for processing files. Additionally, it covers binary file operations and functions like fwrite and fread for handling binary data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT V - FILE PROCESSING

Files – Types of file processing: Sequential access, Random access – Sequential


access file - Random access file - Command line arguments.
5.1 FILES
A file is a collection of related data stored in secondary storage such as hard disk. It
represents a sequence of bytes on the disk which are logically contiguous but may not
be physically contiguous on disk. File is created for permanent storage of data.
A file is a collection of records. A record is one complete set of fields . A field is a
single piece of information. Collection of files is a directory. example, a telephone
book , Employee database, etc
In C language, we use pointer of file type to declare a file.
FILE *fp;
Why files are needed?
 Efficiency : When a program is terminated, the entire data is lost. Storing
in a file will preserve our data even if the program terminates.
 Reusability : If we have to enter a large number of data, it will take a lot of
time to enter them all. However, if we have a file containing all the data, we
can easily access the contents of the file using few commands in C.
 Portability : We can easily move your data from one computer to another.

Types of Files
A file can be classified into two types based on the way the file stores the data.
They are: 1. Text files 2. Binary files
1. Text files
 A text file contains data in the form of ASCII characters
 Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
 You can easily edit or delete the contents.
 They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
2. Binary files
 A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII
characters.
 They are generally stored with .bin file extension
 They can hold higher amount of data, are not readable easily and provides a
better security than text files.
Stream: Stream is a sequence of data bytes, which are used to read and write data
to a file. It is of two types – Input Stream and Output Stream.
Input Stream gets the data from different input devices such as keyboard and
provides input data to the file/program. Output Stream gets the data from the
file/program and write that data on output devices such as monitor or to memory.

Functions used for file operations in C


C provides a number of functions that helps to perform basic file operations
FUNCTION DESCRIPTION
 fopen() create a new file or open a existing file
 fclose() closes a file
 getc() reads a character from a file
 putc() writes a character to a file
 fscanf() reads a set of data from a file
 fprintf() writes a set of data to a file
 getw() reads a integer from a file
 putw() writes a integer to a file
 fseek() set the position to desire point
 ftell() gives current position in the file
 rewind() set the position to the beginning point
5.2 General Steps for Processing a File (or File Operations)
a) Declare a file pointer variable or Creating a file
b) Open a file using fopen() function.
c) Process the file using the suitable function (Reading and Writing into the file)
d) Close the file using fclose() function.

a) Declare a file pointer variable or Creating a file


While working or creating a file, you need to declare a pointer of type file. This
declaration is needed for communication between file and program.
Syntax : FILE *ptr;
*ptr is the FILE pointer, which will hold the reference to the file.

b) Opening a file using fopen() function


Opening a file is performed using library function fopen(). The syntax for
opening a file in standard I/O is:
FILE * fopen(const char *file_name, const char *mode_of_operation);
Here filename is the name of the file to be opened and mode specifies the purpose
of opening the file
MODE DESCRIPTION
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and appending mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
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 appending mode

Read Mode (r) : Read mode is used to read data from existing file . If the file
doesn't exists already, error occurs
Write Mode (w) : Write mode is used to write data into file. If the file has data
already, it is deleted. New file is created if it doesn't exists already. In write mode, the
cursor is positioned at the beginning of the file.

Append Mode (a) : Append mode is used to append or add data to the existing data
of file. New file is created if it doesn't exists already. In Append mode, the cursor is
positioned at the end of the present data in the file.
c. Processing the file (Input/Output operation on File)

i) Writing to a file using fprintf( ) and Reading Data Using fscanf( )

fprintf() : fprintf() is used to write data into a text file. It works just like printf()
except that its first argument is a file pointer. It is used to write data into a file.
Syntax: fprintf (FILE * stream, const char *format …..);

Example : fprintf (fptr, "Hello World!\n");


fprintf (fptr, “%d %d”, a, b);

fscanf() : fscanf() is used to read the data from a file


Syntax: fscanf (FILE * stream, const char *format …..);

Example: fscanf(fptr,"%s %d %d", ename,&age,&sal);

//Example Program for fprinf() and fscanf()


#include <stdio.h>
#include<conio.h>
void main()
{
int age;
int sal;
char ename[50];
FILE *fptr; clrscr();
fptr = fopen("emp.txt","w");
printf("Enter Name, Age, Salary\n");
scanf("%s %d %d",ename,&age,&sal);
fprintf(fptr,"%s %d %d",ename,age,sal);
fclose(fptr);
fptr = fopen("emp.txt","r");
fscanf(fptr,"%s %d %d", ename,&age,&sal);
printf("\n Emp Name=%s \n Age=%d \n Salary=%d",ename,age,sal);
fclose(fptr);
getch();
}

ii) Writing and reading using fgets() and fputs():


fputs()
This function writes a string to the specified stream upto but not including the null
character.
Syntax: fputs(const char *str, FILE *stream)

Example : Eg : fputs(“Hello", fp);

Parameters
str − This is an array containing the null-terminated sequence of characters to
be written.
stream − This is the pointer to a FILE object
fgets( )
This function reads a line from a stream and stores it in a specified string. The
function stops reading text from the stream when either n - 1 characters are read,
the newline character ('\n') is read or the end of file (EOF) is reached.

Syntax: fgets(char *str, int n, FILE *stream)


Example : fgets(str, 60, fp)
Parameters
 str − This is the pointer to an array of chars where the string read is stored.
 n − This is the maximum number of characters to be read (including the final
null-character). Usually, the length of the array passed as str is used.
 stream − This is the pointer to a FILE object .
It returns NULL if there is an error (such as EOF).

Example Program for fputs() and fgets()


#include <stdio.h>
#include <conio.h>
int main ()
{
char str[60];
FILE *fp;
fp = fopen("file.txt", "w+");

clrscr();
fputs("This is c programming.", fp);
fclose(fp);

fp = fopen("file.txt" , "r");
if( fgets (str, 60, fp)!=NULL )
{
puts(str);
}
fclose(fp);
getch();
return(0);
}

iii) Writing and reading using fputc() and fgetc() in C

fputc()
fputc() is used to write a single character at a time to a given file. It writes the given
character at the position denoted by the file pointer and then advances the file
pointer.
This function returns the character that is written in case of successful write operation
else in case of error, EOF is returned.
SYNTAX: fputc(int char, FILE *stream)
Example : fputc(ch, fp)
Parameters
 char -- This is character to be written. This is passed as its int promotion.
 stream -- This is the pointer to a FILE object.
fgetc()

fgetc() is used to obtain input from a file single character at a time. It returns the
character present at position indicated by file pointer. After reading the character, the
file pointer is advanced to next character. If pointer is at end of file or if an error
occurs, EOF file is returned by this function.

SYNTAX: fgetc(FILE *pointer)


Example: fgetc(fp)
Return Value:
If there are no errors, the same character that has been written is returned. If
an error occurs, EOF is returned and the error indicator is set.

Example Program for fputc() and fgetc()


#include <stdio.h>
#include <conio.h>
void main ()
{
FILE *fp;
int ch;
char c;
clrscr();
fp = fopen("file.txt", "w+");
for( ch = 97 ; ch <= 100; ch++ )
{
fputc(ch, fp);
}
fclose(fp);

fp = fopen("file.txt","r");
do
{
c = fgetc(fp);
if (feof(fp))
break ;
printf("\n %c", c);
}
while(1);
fclose(fp);
getch();
}
d.Closing a file using fclose() functions
A file needs to be closed after a read or write operation to release the memory
allocated by the program. In C, a file is closed using the fclose() function. This
returns 0 on successful closure and EOF in the case of a failure The fclose()
function is used to close an already opened file. If we fail to close the file before the
program terminates, the operating system will close the file as part of its
housekeeping function.

SYNTAX:-fclose(ptr);
Example:- fclose(fptr);
5.3 Other functions related to files
feof ( ) function :
The feof () function inquires about the end-of-file character (EOF) in a file. If EOF has
been detected, a nonzero value is returned. Otherwise, a value of 0 is returned.

Syntax : feof()

Example:

#include <stdio.h>
int main ()
{
FILE *fp = fopen("test.txt","r");
if (fp == NULL)
return 0;
do
{
c = fgetc(fp);
if (feof(fp))
break ;
printf("%c", c);
}
while(1);
fclose(fp);
return(0);
}

rename() function:
The rename() function change the name of a file to a new one.

Syntax : int rename ( const char * oldname, const char * newname );

Eg :
#include <stdio.h>
int main()
{
char *oldname = "test.txt";
char *newname = "new_test.txt";
if (rename(oldname, newname) == 0)
printf("The file %s was renamed to %s.", oldname, newname);
else
printf("Error renaming the file %s.", oldname);
return 0;
}

remove() function:
The remove() function is be used to delete a file. The function returns 0 if the file is
deleted successfully, Otherwise, it returns a non-zero value. The remove() is defined
inside the <stdio.h> header file.

Syntax : remove("filename");
Eg :
#include <stdio.h>
int main()
{
if (remove("abc.txt") == 0)
printf("Deleted successfully");
else
printf("Unable to delete the file");

return 0;
}

ferror() function:
The ferror() function check for an error in reading from or writing to the given stream. If an I/O
error has occurred, a nonzero value is returned. Otherwise, a value of 0 is returned.

fflush() function:
The fflush() function is used to empty the buffer that is associated with the specified
output stream

fgetpos() function:
The fgetpos() function is used to store the current position of the file pointer that is
associated with stream

ftell() function:
The ftell() function is used to obtain the current value of the file-position indicator for
the stream pointed to by stream.

5.4 Binary Files


 Depending upon the way file is opened for processing, a file is classified into
text file and binary file.
 If a large amount of numerical data it to be stored, text mode will be
insufficient. In such case binary file is used.
 Working of binary files is similar to text files with few differences in opening
modes, reading from file and writing to file.

Opening modes of binary files


Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference
between opening modes of text and binary files is that, b is appended to
indicate that, it is binary file.

Reading and writing of a binary file using fwrite() and fread() functions
Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.

fwrite() : Function fwrite() takes four arguments, address of data to be written in


disk, size of data to be written in disk, number of such type of data and pointer to the
file where you want to write.
Syntax:-
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Example :
fwrite(&emp, sizeof(emp), 1, fp)

fread(): Function fread() also take 4 arguments similar to fwrite() function as above.
Syntax:- fread(address_data,size_data,numbers_data,pointer_to_file);
Example:
fread(&emp, sizeof(emp), 1, fp)
Where,
ptr is a pointer which points to the array which receives structure.
Size is the size of the structure
nst is the number of the structure
fptr is a file pointer.

Example program :
// binary file - reading and writing
#include<stdio.h>
#include<stdlib.h>
# include <conio.h>
int main()
{
struct employee
{
char name[50];
int age;
float salary;
} emp;
FILE *fp;
clrscr();
fp = fopen("employee.txt", "wb");
printf("\nEnter details of employee \n");
printf("\nName: ");
scanf(”%s”,emp.name);
printf("\nAge: ");
scanf("%d",&emp.age);
printf("\nSalary: ");
scanf("%f",&emp.salary);
fwrite(&emp, sizeof(emp), 1, fp);
fclose(fp);

fp=fopen("employee.txt", "rb");
fread(&emp,sizeof(emp),1,fp);
printf("\nEmployee name is %s",emp.name);
printf("\nEmployee age is %d",emp.age);
printf("\nEmployee salary is %.2f",emp.salary);
printf("\nOne record read successfully"); getch();
return 0;
}

OUTPUT:
Enter details of employee
Name: AAA
Age: 22
Salary: 10000
Employee name is AAA
Employee age is 22
Employee salary is 10000.00
One record read successfully

Comparisons:

a) read and write mode


S.No read Mode Write Mode
1 Read mode is used to read data from Write mode is used to write data into
existing file file. If the file has data already, it is
deleted
2 Error occurs if the file doesn't exists New file is created if it doesn't exists
already already

b) Append and Write Mode


S.No Append Mode Write Mode
1 Append mode is used to append or Write mode is used to write data into
add data to the existing data of file file. If the file has data already, it is
deleted
2 New file is created if it doesn't exists New file is created if it doesn't exists
already already
3 In Append mode, the cursor is In write mode, the cursor is
positioned at the end of the present positioned at the beginning of the
data in the file. file.

c) getc() and getchar()


S.No getc() getchar()
1 The getc() reads one character from The getchar() is capable of reading
any input stream from the standard input
2 Syntax Syntax :
getc(FILE *stream); getchar(void);
3 // Example for getc() in C / Example for getchar() in C
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
printf("%c", getc(stdin)); printf("%c", getchar());
return(0); return 0;
} }
d) read and write mode
S.No fseek() Rewind()
1 rewind is used to move the file
fseek is used to move the file
pointer to the beginning of the file
pointer to a specific position. stream.
2 It returns 0, if successful Does not have return value
e) scanf() and fscanf()

S.No scanf() fscanf()


1 It is used to read standard input. This function is used to read input
from a file
2 Syntax Syntax :
scanf(“ control string”, &variables) fscanf (FILE * stream, const char
*format …..);
3 Eg : scanf("%d", &a); Eg :fscanf (fptr, “%d %d”,&x, &y);

f) printf() and fprintf()

S.No printf() fprinf()


1 It is used to print in the standard fprintf is used to print the string
output. content in file
2 Syntax : Syntax :
printf(“Control String”, variables); fprintf (FILE * stream, const char
*format …..);

3 Eg: printf("hello"); fprintf (“%d %d”, a, b);

g) feof() and ferror()

S.No feof() ferror()


1 The feof () inquires about the end-of- The ferror()inquires about input or
file character (EOF) in a file output errors in a file
2 If EOF has been detected, a nonzero If an I/O error has occurred, a
value is returned. Otherwise, a value nonzero value is returned. Otherwise,
of 0 is returned a value of 0 is returned.

5.5 Sequential and Random Access File Handling in C


In computer programming, the two main types of file handling are:
 Sequential access
 Random access.

Sequential files are generally used in cases where the program processes the data
in a sequential order – Eg: reading cassette tape

Random files are generally used in cases where the data should be read or written
at any point in file, rather than having to process it sequentially. Eg: reading CD

A hybrid approach is also possible whereby a part of the file is used for sequential and
part of the file is used to locate something in the random manner in the file.
Sequential access :
Sequential file access is the most straightforward method of accessing files. This
method accesses data as one record at a time by starting from the beginning of the file to
its end. Moreover, the records are read or written in the order they appear in the file. A
common example of sequential access is with a tape drive, where the device must move
the tape's ribbon forward or backward to reach the desired information

Advantages of sequential file organization


 It is an efficient method for handling the huge amount of data.
 In this method, files can be easily stored in cheaper storage mechanism like magnetic
tapes.
 It is simple in design

Example For sequential access:


// Finding average of numbers stored in sequential access file
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int num[10],sum=0,i,n;
float avg;
fp=fopen("num.txt","w");
printf("\n Enter the total numbers\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Num:");
scanf("%d",&num[i]);
fwrite(&num,sizeof(int),1,fp);
}
fclose(fp);
fp=fopen("num.txt","r");
for(i=0;i<n;i++)
{
fread(&num,sizeof(int),1,fp);
sum=sum + num[i];
}
avg=(float)sum/n;
printf("\n the average of numbers is .2%f", avg);
fclose(fp);
getch();
}

Output :
Enter the total numbers
3
Enter the Num:10
Enter the Num:20
Enter the Num:30
the average of numbers is 20.00

Example 2 : Write A Program To Count The Number Of Account Holders


Whose Balance Is Less Than The Minimum Balance
// USING SEQUENTIAL ACCESS FILE. PROGRAM

#include<stdio.h>
#include<stdlib.h>
struct customer
{
char name[20];
int acct_num;
int acct_balance;
}cust[10];
void main()
{
FILE *fp;
int i,n;
int min=5000;
clrscr();
fp=fopen("accounts.txt","w");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
printf("\n Enter accounts information\n\n");
printf("enter total number of account information");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Name:");
scanf("%s",cust[i].name);
printf("Acct Num:");
scanf("%d",&cust[i].acct_num);
printf("Balance:");
scanf("%d",&cust[i].acct_balance);
fwrite(&cust,sizeof(struct customer),1,fp);
}
fclose(fp);
fp=fopen("accounts.txt","r");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
else
{
printf("\n File opened for reading: accounts.txt\n\n");
}
for(i=0;i<n;i++)
{
fread(&cust,sizeof(struct customer),1,fp); if(cust[i].acct_balance<=min)
{
printf("\n Name=%10s \n Acct Num =%8d \n Balance=%8d",
cust[i].name,cust[i].acct_num,cust[i].acct_balance);
}
}
getch(); fclose(fp);

}
OUTPUT:
Enter accounts information
Enter total number of account information 2
Name: NNN
Acct Num : 1
Balance: 10000
Name : AAA
Acct Num: 2
Balance: 4500
File opened for reading : accounts.txt
Name= AAA
Acct Num=2
Balance=4500.00
Random Access To File
Random access file in C enables us to read or write any data in our disk file without
reading or writing the data before it. ftell() is used to find the position of the file
pointer from the starting of the file. rewind() is used to move the file pointer to the
beginning of the file. There is no need to read each record sequentially , if we want to
access a particular record. C supports the following functions for random access file
processing. These are also called File management functions for random access

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

fseek():
This function is used for moving the pointer position in the file at the specified byte.

Syntax: fseek( file pointer, displacement, pointer position);


Where
file pointer is the pointer. Displacement 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.

It can be one of three values:


 SEEK_SET – from the start;
 SEEK_CUR – from the current position;
 SEEK_END – from the end of the file.

Examples:
1. fseek( p,10L, SEEK_SET)
The pointer position is skipped 10 bytes from the beginning of the file.
2. fseek( p,5L, SEEK_CUR)
The pointer position is skipped 5 bytes forward from the current position.
3. fseek(p,-5L, SEEK_CUR)
The 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
counted 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.
//Example program for Random Access to file:
(Program to append content of an existing file)
#include <stdio.h>
#include<conio.h>
void main ()
{
FILE *fp;
int c;
clrscr();
fp = fopen("sample.txt","a+");
fputs("This is sample file", fp);
// fseek() is used to shift the file pointer to the 8th position.
fseek(fp, 8, SEEK_SET );
//Overwrite to Programming in C in the 8th position
fputs("Programming in C", fp);
// prints the current position of the file pointer using ftell()
printf("The current position of the file pointer is: %ld\n", ftell(fp));
//Move file pointer to the beginning of the file.
rewind(fp);
//To verify if rewind() worked using ftell().
printf("The current position of the file pointer is: %ld\n", ftell(fp));
while(1)
{
c = fgetc(fp);
if(feof(fp) ) Output :
{
break; The current position of the file pointer is 24
}
printf("%c", c); The current position of the file pointer is 0
}
getch(); This is Programming in C
}

Compare Sequential access and Random access file (or) case study of “How
sequential access file differ from random access file”

Parameter Sequential Access Random Access

Random access files allow


Access Sequential access files allow
direct access to specific
Method access to records in a sequential
records using an index, record
manner
number, or key.
Sequential access files are
slower compared to random Random access files, on the
Access access files since accessing a other hand, allow direct access
Speed specific record requires reading to specific records, resulting in
through all the previous records faster access times.
in the file
Record Sequential access files store Random access files do not
Ordering records in a specific order have any specific order
Random access files may
Inserting a new record in a
require relocating other
Insertion sequential access file is
records to maintain the order
of New relatively easy since new
so insertion becomes hard as
Record records are added to the end of
compared to sequential
the file. access.
Sequential access files require
Memory less memory than random Random access files require
Requirem access files since they do not more memory because of
ents need to store any indexing indexing information
information.
Search Search flexibility is limited in Random access files offer
Flexibility sequential access file. higher search flexibility
Record In sequential access files, record Random access files, record
Sizes sizes are usually uniform sizes can be variable

fseek() vs ftell()

S.No fseek() ftell()


1 fseek() is used to relocate the file ftell() is used to give the current file
pointer position
2 Syntax: Syntax : ftell(fp)
fseek( file pointer, displacement,
pointer position);

fseek() vs rewind()

S.No fseek() rewind()


1 fseek is used to move the file pointer rewind is used to move the file pointer
to a specific position. to the beginning of the file stream.
2 Syntax: Syntax:
fseek(FILE *stream, offset, position); void rewind(FILE *stream);
3 It returns 0 if successful, and a non-
It does not return any value.
zero value if an error occurs.

Command line arguments


Command-line arguments are the parameters that are given on the system's
command line, and the values of these arguments are passed on to the program
during program execution. The arguments passed in command line are:
1. argc
2. argv[]
where,
argc – Number of arguments in the command line including program name. It is of
integer datatype
argv[]– This has all the arguments in the command line. This holds string values
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.
In real time application, we can pass arguments to the main program itself.
These arguments are passed to the main () function while executing .exe file from
command line. For example, when we compile the example program (test.c), we get
executable file in the name “test”. Now, the 4 arguments in command line look like
below.
C:\TC\SOURCE>test hello world
argc = 3
argv[0] = C:\TC\SOURCE\TEST.EXE
argv[1] = Hello
argv[2] = World

Properties of Command line arguments


 These are the arguments passed to the program during execution
 They are handled in main function using args.
 argc refers to the no. of arguments and argv[] which is the pointer array
 argv[0] holds the name of the program
 argv[1] has the first command line argument and argv[n] has the last
command line argument

Procedure: To execute command line arguments


1. Save your file with name test.c
2. Compile and Execute the program
Eg : if test.c is the program, test.exe is its executable file
3. Open dos shell. Type the following:
C:\TC>BIN\cd..
C:\TC>cd SOURCE
C:\TC\SOURCE>test Hello world
test.c is the program and test.exe is its executable file

// Example Program for Command line arguments


#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("No. of Arguments passed through command line is %d",argc);
printf("\n Program name : %s \n", argv[0]);
printf("argv[1] = : %s \n", argv[1]);
printf("argv[2] = : %s \n", argv[2]);
return 0;
}

OUTPUT: No. of Arguments passed through command line is 3


Program name : c:\turboc\source\file.c
argv[1] : Hello
argv[2] : world
Example 2 : C Program to Generate Fibonacci Series using Command Line
Argument
//FIBONACCI SERIES
#include <stdio.h>
void main(int argc, char * argv[])
{
int n, f1= 0, f2 = 1, f, cnt;
printf("No. of Args = %d",argc);
n = atoi(argv[1]);
printf("\n Printing fibonacci nos: ", n);
printf("%d ", f1);
printf("%d ", f2);
cnt = 2;
while (cnt< n)
{
f= f1+f2;
f1 = f2;
f2 = f;
printf("%d ", f);
cnt++;
}
}
OUTPUT: C:\TC\SOURCE>>fib 5
Printing first 10 fibonacci nos. 0 1 1 2 3

Example 3 : To write a C Program to find factorial of given number using


command line argument

# include <stdio.h>
int main(int argc, char* argv[])
{
int i,n, fact = 1;
printf("No. of arguments = %d",argc);
n = atoi(argv[1]);
// Find the factorial
for (i = 1; i <= n; i++)
{ fact = fact * i; }
printf(" Factorial = %d", fact);
getch();
return 0;
}

OUTPUT:
>> pgm 5
Factorial = 120
C- Files Examples:-

1. Write a C program to read a file and display the content of the file.

#include <stdio.h>
int main ()
{
FILE *fp = fopen("test.txt","r");
if (fp == NULL)
return 0;
do
{
c = fgetc(fp);
if (feof(fp))
break ;
printf("%c", c);
}
while(1);
fclose(fp);
return(0);
}

2. Write a C program to read name and marks of n number of students


from user and store them in a file. If the file previously exits, add the
information of n students.
#include <stdio.h>
int main()
{
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL)
{
printf("Error!");
exit(1);
}

for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\n Name: %s \n Marks=%d \n",name, marks);
}
fclose(fptr);
return 0;
}
3. Write a C program to write all the members of an array of structures to
a file using fwrite(). Read the array from the file and display on the screen.
#include<stdio.h>
#include<conio.h>
struct s
{
char name[50];
int height;
};
int main()
{
struct s a[5],b[5];
FILE *fptr;
int i;
clrscr();
fptr=fopen("file.txt","wb");

for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\n Height: %d", b[i].name,
b[i].height);
}
fclose(fptr);
getch();
}

4. Write a C program to copy the contents of one file into another.

#include <stdio.h>
#include <stdlib.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);
return 0;
}

5. Write a C Program to show Transaction processing using random access files


#include<stdio.h>
#include<stdlib.h>
struct customer
{
char name[20];
int acct_num;
int acct_balance;
}cust;
void main()
{
FILE *fp;
int choice=1,n;
fp=fopen("accounts.txt","w");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
printf("\n Enter accounts information\n\n");
do
{
printf("\n Name:");
scanf("%s",cust.name);
printf("Acct Num:");
scanf("%d",&cust.acct_num);
printf("Balance:");
scanf("%d",&cust.acct_balance); fwrite(&cust,sizeof(struct
customer),1,fp);
printf("Press 1 to enter one more entry:\n");
scanf("%d",&choice);
}
while(choice==1); fclose(fp);
fp=fopen("accounts.txt","r");
printf("\n File opened for reading: accounts.txt\n\n");
printf("\n Enter which customer detail has to be printed");
scanf("%d",&n);
fseek(fp,n*sizeof(struct customer),0);
fread(&cust,sizeof(struct customer),1,fp);
printf("\n Name=%10s Acct Num =%8d Balance=%d\n",
cust.name,cust.acct_num,cust.acct_balance);
getch();
}

6. Write a C Program to find the size of a file


#include <stdio.h>
#include <conio.h>
int main()
{ long int size;
FILE* fp = fopen("a.txt", "r");
clrscr();
if (fp==NULL)
{
printf("Unable to open");
}
fseek(fp, 0L, SEEK_END);
// calculating the size of the file
size = ftell(fp);
printf("\n Size of the file = %d ", size);
fclose(fp);
getch();
return 0;
}
7. Write a C Program to convert lower case to upper case using file
#include <stdio.h>
void main ()
{
FILE *fp;
int c;
clrscr();
fp = fopen("sample.txt","w+");
fputs("this is sample text", fp);
rewind(fp);
while(1)
{
c = fgetc(fp);
if(feof(fp) )
{
break;
}
printf("%c", toupper(c));
}
}

8. Write a C Prgrom to Merge two files and store to another file


/* C Prgrom to Merge two files and store to another file */
#include <stdio.h>
# include <conio.h>
int main()
{
FILE *fp1,*fp2,*fp3;
int count =0; // Line counter (result)
char c; // To store a character read from file
clrscr();
fp1 = fopen("a.txt", "r");
fp2 = fopen("b.txt", "r");
fp3 = fopen("c.txt", "w");
// Check if file exists
if (fp1 == NULL|| fp2 == NULL || fp3==NULL)
{
printf("Could not open file ");
return 0;
}

// Extract characters from file and store in character c


while ((c= fgetc(fp1)) !=EOF)
{
fputc(c,fp3);
}
while ((c= fgetc(fp2)) !=EOF)
{
fputc(c,fp3);
}
printf("The file c.txt has the content of a and b ", count);
// Close the file
fclose(fp1);
fclose(fp2);
fclose(fp3); getch();
return 0;
}

9. Write a C Program to count the Number of Lines, characters, words in a


Text File

#include <stdio.h>
# include <conio.h>
int main()
{
FILE *fp;
int line =1, word=1, ch=1;
char c; // To store a character read from file
clrscr();
fp = fopen("b.txt", "r");

// Check if file exists


if (fp == NULL)
{
printf("Could not open file ");
return 0;
}

// Extract characters from file and store in character c


while ((c=fgetc(fp)) !=EOF)
{ if (c=='\n')
line++;
if (c==' '||c=='\n')
word++;
else
ch++;
}
// Close the file
fclose(fp);
printf("The file has %d characters\n ", ch);
printf("The file has %d words\n ", word);
printf("The file has %d lines\n ", line);
getch();
return 0;
}
10. Write a C Program to list the files in a Directory
#include <dirent.h> // contains functions that facilitate directory traversing
#include <stdio.h>
int main(void)
{
DIR *d; // The DIR data type represents a directory stream
struct dirent *dir;
// A dirent structure contains the character pointer d_name, which points to a string that
// gives the name of a file in the directory.
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{ printf("%s\n", dir->d_name); }
closedir(d);
}
return(0);
}
11. Write a C program for the reversing the content of file
#include <stdio.h>
#include <string.h>
void main()
{
long int size;
char ch;
FILE *fp1,*fp2;
fp1 = fopen("a.txt", "r");
if (fp1 == NULL)
{
printf("Unable to open file\n");
return;
}
else
{
fseek(fp1,0L,SEEK_END);
size=ftell(fp1);
fp2 = fopen("b.txt", "w");
while (size>0)
{
ch=fgetc(fp1);
fputc(ch,fp2);
fseek(fp1,-2L,SEEK_CUR);
size--;
}
}
printf("\nFile copied to b in reverse");
fclose(fp1);
fclose(fp2);
}
SUMMARY OF FILE HANDLING FUNCTIONS
File Declaration Description
operation
fopen() FILE *fopen (const char*filename,const char *mode) fopen() function is
FILE *fp; used to open a file to
(or) perform operations
fp=fopen(“filename”,”mode”); such as reading,
where, writing etc.
fp-file pointer to the data type “FILE”.
filename-the actual file name with full path of the file.
mode-refers to the operation that will be performed
on the file.
Example:r,w,a,r+,w+, a+,rb,wb,ab

fclose() int fclose ( FILE *fp); fclose() function


(or) closes the file that is
fclose (fp); being pointed by file
pointer fp.
fgets() char *fgets(char *string,int n, FILE *fp); Fgets() function is
(or) used to read a file line
fgets (string,size,fp); by line
where,
size-size of the string
fp-file pointer
fputs() int *fputs(const char *string, FILE *fp) fputs () function
(or) writes string into a
fputs(”string”,fp); file pointed by fp

gets() char * gets(char *string) gets () functions is


(or) used to read the
gets (string); string from keyboard
input.
puts() int puts(const char *string) puts() function is
(or) used to write a line to
puts(string); the output screen.
where,
String-data that should be displayed on the output
screen

putw() int putw(int number,FILE *fp); putw () function is


(or) used to write an
putw(i,,fp); Integer into a file.
Where
i – integer value
fp – file pointer

getw() int getw(FILE*fp); getw function reads


(or) an integer value from
getw(fp) a file pointed by fp.
File Declaration Description
operation
fgetc() int fgetc(FILE*fp) fgetc() function is
(or) used to read a
fgetc(fp); character from a file.it
Where, reads single character
fp-file pointer at a time.
fputc() int fputc(int char,FILE*fp) fputc() function is
(or) used to write a
fputc(ch,fp); character into a file.
where,
ch – character value
fp – file point
feof() int feof(FILE*fp) feof()functions is used
(or) to check for the end
feof(fp); of a file.
Where,
fp –file pointer
getchar() getchar(void) getchar() function is
(or) used to get/read a
getchar(); character from
keyboard input
putchar() putchar(char); putchar() function is
Where,char is a character variable/value. used to write a
character on standard
output/screen
fscanf() int fscanf(FILE *fp, const char *format,…) fscanf() function is
(or) used to read
fscanf (fp,”Format ”, & var1,&var2,.); formatted data from a
where, fp is file pointer to the data type “FILE”, file
var1,var2,.. – variable names

fprintf() int fprintf(FILE *fp, const char *format, . . . ) fprintf() function is


(or) used to write
fprintf(fp,”format”, var1,var2,…); formatted data into a
where,fp is file pointer to the data type “File”. file.
var1,var2,.. – variable names

ftell() long int ftell(FILE *ftp) ftell() function is used


(or) to get current position
ftell(fp); of the file pointer.

rewind() void rewind (FILE *fp) rewind () function is


(or) used to move file
rewind(fp); pointer position to the
beginning of the file.
fseek() int fseek (FILE *fp, long int offset, int whence) fseek() function is
(or) used to move file
fseek( fp, displacement, pointer position); pointer position to the
where, given location.
File Declaration Description
operation
fp - file pointer
displacement – Number of bytes/characters to be
offset/moved from whence/the current file pointer
position)
position – This is the current file pointer position from
where offset is added. Below 3 constants are used to
specify this.
SEEK_SET SEEK_SET It moves file pointer
position to the
beginning of the file

SEEK_CUR SEEK_CUR It moves file pointer


position to given
location.
SEEK_END SEEK_END It moves file pointer
position to the end of
file.
fflush() int fflush(FILE *fp) fflush() function is
(or) used to flush/clean
fflush (buffer), the file or buffer.
Where, buffer is a temporary variable or pointer
which loads/points the data.

remove() int remove(const char * filename) remove() function is


(or) used to delete a file.
remove(“file_name”);
where, file_name should be the name of the file with
full path name.

rename() int rename ( const char * oldname, const char * The rename() functio
newname ); n change the name of
(or) a file to a new one
rename(“old name”,”new name”);

ferror() int ferror(FILE *fp) The ferror()


(or) function check for an
ferror(fp) error in reading from
or writing to file

fread() fread(address_data,size_data,numbers_data,pointer fread() is used for


_to_file); reading large data
from a file
fwrite() fwrite(address_data,size_data,numbers_data,pointer fwrite() is used for
_to_file); writing large date to a
file
PART A

Q.No Questions
1. Define file. Why are files needed?
2. Mention different type of file accessing.
3. Distinguish between Sequential access and Random access.
4. What is meant by command line argument? Give an example.
5. List out the various file handling function.
6. Compare fseek() and fell() function
7. How to create a file in C?
8. Identify the various file operation modes and their usage.
9. How to read and write the file?
Examine the following:
10.  getc() and getchar()
 scanf() and fscanf()
Distinguish between following:
11.  printf() and fprintf()
 feof() and ferror()
12. Mention the functions required for Binary file I/O operations.
13. Identify the different types of file.
14. Identify the difference between Append and Write Mode.
15. What is the use of rewind () functions.
16. What will be the impact if 'fclose()' function is avoided in a file handling C program?
17. Write a C Program to find the Size of a File.
18. Write the Steps for Processing a File
19. Write a code in C to defining and opening a File.
20. Why do we use command line arguments in C?
21. What does argv and argc indicate in command-line arguments ?
22. Compare the terms Field, Record and File.
23. Compare text files and Binary files

24. What are two main ways a file can be organized ?


Give an example for fseek()
25.
PART - B
1. What is file? What are facilities available in language C to handle files? Explain.
Distinguish between the following functions.
2. a) getc() and getchar(). b) scanf() and fscanf().
c) printf() and fprintf(). d) feof() and ferror()
3. Illustrate and explain a C program to copy the contents of one file into another.
Explain the various file accessing policies available in language C with appropriate
4.
programs. (Sequential & random access)
5. Explain the read and write operation on a file suitable program.
Explain the types of file processing with necessary examples. (Sequential & random
6.
access)
7. Describe the various functions used in a file with example.
Explain in detail random access in files along with the functions used for the same in
8.
C. Give suitable examples.
9. Write a C Program to read content of a File and display it.
10. Write a C Program to print the contents of a File in reverse.
11. Write a C Program Transaction processing using random access files.
12. Write a C program Finding average of numbers stored in sequential access file.
13. Explain about command line argument with suitable example.
14. Compare Sequential access and Random access file.
Write a C Program to calculate the factorial of a number by using the command line
15.
argument.
16. Write a C Program to generate Fibonacci series by using command line arguments.
Write a C program to get name and marks of 'n' number of students from user and
17.
store them in a file.
Write a C program to read name and marks of 'n' number of students from user and
18. store them in a file. If the file previously exists then append the information into the
existing file.
Write a C program to write all the members of an array of structures to a file using
19.
fwrite(). Read the array from the file and display on the screen.
Write short notes on file functions in c
20.
fseek(), ftell(),frewind(),feof(), fscanf()
21. Discuss about the modes of file handling?
Write the case study of “How sequential access file differ from random access
22.
file”?
Explain in detail random access files along with the functions used for the
23. same in C. Give suitable examples
24. Write a C Program to read content of a File and display it
Write a C Program to calculate the Fibonacci series using the command line
25.
argument.

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