SlideShare a Scribd company logo
1 of 39
Unit 5
Part –A
1. Define file.
 A file represents a sequence of bytes on the disk where a group of related data is
stored. (Or)
 A file is a collection of records.
2. Mentiondifferenttype of file accessing.
 SequentialaccessandRandomaccess
When dealing with files, there are two types of files they are:
1. Text files and 2. Binary files.
3. DistinguishbetweenSequentialaccessandRandomaccess.
Sequential files are generally used in cases where the program processes the data in
a sequential fashion – i.e. counting words in a text file
True random access file handling, however, only accesses the file at the point at
which the data should be read or written, rather than having to process it sequentially.
4. What ismeantby commandline argument.?Give anexample.
 Command-line arguments are given after the name of the program in command-line
shell of Operating Systems. To pass command line arguments, we typically define main()
with two arguments : first argument is the number of command line arguments and
second is list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
5. List outthe variousfile handlingfunction.
There are many functions in C library to open, read, write, search and close
file. A list of file functions are given below:
Function Description
fopen() opens new or existing file
fprintf() write data into file
fscanf() reads data from file
fputc() writes a character into file
fgetc() reads a character from file
fclose() closes the file
fseek() sets the file pointer to given position
fputw() writes an integer to file
fgetw() reads an integer from file
ftell() returns current position
rewind() sets the file pointer to the beginning of the file
6. Compare fseek()andftell() function.
fseek()
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek (file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
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.
This sets the pointer position in the file.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
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.
7. How to create a file inC ?
File canbe createdas follows:
o Declare a file pointer variable.
o Open a file using fopen() function.
o Process the file using the suitable function.
o Close the file using fclose() function
Example:
FILE *fp = NULL;
fp = fopen("textFile.txt" ,"w");
8. Why filesare needed?
 Filesare neededforthe computerthatstoresdata,information,settings,orcommandsused
witha computerprogram.
 When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
 You can easily move your data from one computer to another without any changes.
9. How to readand write the file.?
 For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that,
fprint and fscanf expects a pointer to the structure FILE.
 r,w,a,w+,r+,a+ modes used for read and write operations.
10. Compare the termsField,RecordandFile.
Field: A single piece of information about an object. If the object were an Employee, a field would
be Firstname, Lastname, or City or State.
Record: A collection of fields. In an Employee file, there would be one record for John Smith,
another record for Mary Jones, and another record for Al Newman.
File: A collection of bytes. The bytes may represent numbers or characters. In business systems,
files usually consist of collections of records.
11. Examine the following:‐
(i) getc() andgetchar()
getc():
It reads a single character from a given input stream and returns the corresponding integer value
(typically ASCII value of read character) on success. It returns EOF on failure.
Syntax:
int getc(FILE *stream);
getchar():
The difference between getc() and getchar() is getc() can read from any input stream, but
getchar() reads from standard input. So getchar() is equivalent to getc(stdin).
Syntax:
int getchar(void);
(ii)scanf andfscanf()
scanf() : The C library function int scanf (const char *format, …) reads formatted
input from stdin.
Type specifiers that can be used in scanf:
%c — Character
%d — Signed integer
%f — Floating point
%s — String
fscanf() : fscanf() is used to read formatted input from a file.
12. Distinguishbetweenfollowing:‐
(i).printf () andfprintf()
ii).feof() andferror()
(i).printf:
printf function is used to print character stream of data on stdout console.
Syntax:
Example:
printf("hello geeksquiz");
fprintf:
fprintf is used to print the sting content in file but not on stdout console.
Example:
fprintf(fptr,"%d.%sn", i, str);
(ii). feof():
It checks ending of a file. It continuously return zero value until end of file not come and return non
zero value when end of file comes.
Syntax:
feof(file pointer);
Example:
FILE *fp;
if(feof(fp)==0)
{
printf(“not eof”); //when end of file not come
}
ferror():
It checks error in a file during reading process. If error comes ferror returns non zero value. It
continuously returns zero value during reading process.
Syntax:
ferror(file pointer);
Example:
if(ferror(fp)==0)
{
printf(“reading”);
}
if(ferror(fp)!=0)
{
printf(“error”);
}
13. Whichof the followingoperationscanbe performedonthe file "NOTES.TXT"usingthe below code?
FILE *fp;
fp = fopen("NOTES.TXT","r+");
Ans.Open an existing file for update (reading and writing).
14. Identifythe differenttypesof file.
A file canbe of twotypes
• Textfile
• Binaryfile
Text files:A textfilecanbe a streamof characters that a computercan processsequentially.A text
streamin C isa special kindof file.Itisnotonlyprocessedsequentiallybutonlyinforwarddirection.
A binary file isdifferenttoatextfile.Itisa collectionof bytes.InCProgrammingLanguage a byte and a
character are equivalent.Nospecialprocessingof the dataoccurs and eachbyte of data istransferredto
or from the diskunprocessed.
15. Identifythe difference betweenAppendandWrite Mode.
Write (w) mode and Append(a) mode,while openingafile are almostthe same.Bothare usedto write
ina file.Inboththe modes,newfileiscreatedif itdoesnotalreadyexist.The onlydifference theyhave
is, whenyouopena file inthe write mode,the file isreset,resultingindeletionof anydataalready
presentinthe file.Whileinappendmode thiswill nothappen.Appendmode isusedtoappendoradd
data to the existingdataof file,if any.Hence,whenyouopenafile inAppend(a) mode,the cursoris
positionedatthe endof the presentdatainthe file.
16. What isthe use of rewind() functions.
The rewind function sets the file position to the beginning of the file for the stream pointed to
by stream. It also clears the error and end-of-file indicators for stream.
Syntax
The syntax for the rewind function in the C Language is:
void rewind(FILE *stream);
17. Write a C Program to findthe Size of a File.
Here is source code of the C Program to find the size of file using file handling function.
1. #include <stdio.h>
2. void main(int argc, char **argv)
3. {
4. FILE *fp;
5. char ch;
6. int size = 0;
7. fp = fopen(argv[1], "r");
8. if (fp == NULL)
9. printf("nFile unable to open ");
10. else
11. printf("nFile opened ");
12. fseek(fp, 0, 2); /* file pointer at the end of file */
13. size = ftell(fp); /* take a position of file pointer */
14. printf("The size of given file is : %dn", size);
15. fclose(fp);
16. }
18. Write the Stepsfor ProcessingaFile
19. Write a code inC to definingandopeningaFile.
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("INPUT.txt","r") // Open file in Read mode
fclose(fp); // Close File after Reading
return(0);
}
20. What doesargv andargc indicate incommand-line arguments?
argv(ARGument Vector) is array of character pointers listing all the arguments.
argc is the number of command line arguments
Part-B
1. Describe the followingfile manipulationfunctions withexamples.(13)
i) rename().(3)
ii) remove().(5)
iii) fflush().(5)
i) rename()’ function can be called to change the name of a file from oldname to newname. If
the file with newname is already existing while ‘rename()’ was called, behaviour is
implementation defined. Both the functions return ZERO when succeed and non-zero value
when they fail. If ‘rename()’ fails, file with original name is yet accessible.
For example, for an existing file “hello.txt”,
rename("hello.txt", "byebye.txt");
They are prototypedbelow:
int rename(char const *oldname, char const *newname);
ii) remove()’ functioncanbe usedtoexplicitlyclose/deleteafile specifiedbyargument.If the specified
file isopenwhile remove() wascalled,behaviourisimplementationdefined.
For example, for an existing file “hello.txt”,
remove("hello.txt");
Theyare prototypedbelow:
int remove(char const *filename);
iii) fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output
buffer and move the buffered data to console (in case of stdout) or disk (in case of file output
stream). Below is its syntax.
fflush(FILE *ostream);
Example:
#include <stdio.h>
#include<stdlib.h>
int main()
{
char str[20];
int i;
for (i=0; i<2; i++)
{
scanf("%[^n]s", str);
printf("%sn", str);
// fflush(stdin);
}
return 0;
}
Input:
geeks
geeksforgeeks
Output:
geeks
geeksforgeeks
2. Distinguishbetweenthe followingfunctions.(13)
a) getc() andgetchar().(3)
b) scanf() and fscanf().(3)
c) printf() andfprintf().(3)
d) feof() andferror().(4)
a) getc():
It reads a single character from a given input stream and returns the corresponding integer value
(typically ASCII value of read character) on success. It returns EOF on failure.
Syntax:
int getc(FILE *stream);
Example:
// Example for getc() in C
#include <stdio.h>
int main()
{
printf("%c", getc(stdin));
return(0);
}
Output: g
getchar():
The difference between getc() and getchar() is getc() can read from any input stream, but
getchar() reads from standard input. So getchar() is equivalent to getc(stdin).
Syntax:
int getchar(void);
Example:
// Example for getchar() in C
#include <stdio.h>
int main()
{
printf("%c", getchar());
return 0;
}
b) The fscanf() function is used to read mixed type form the file.
Syntaxof fscanf()function
fscanf(FILE *fp,"format-string",var-list);
The fscanf() function is similar to scanf() function except the first argument which is a file
pointer that specifies the file to be read.
Exampleoffscanf()function
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("file.txt","r"); //Statement 1
if(fp == NULL)
{
Printf ("nCan't open file or file doesn't exist.");
exit(0);
}
printf("nData in file...n");
while((fscanf(fp,"%d%s%f",&roll,name,&marks))!=EOF)
//Statement 2
printf("n%dt%st%f",roll,name,marks);
fclose(fp);
}
Output :
Data in file...
1 Kumar 78.53
2 Sumit 89.62
int scanf(const char *format, ...) reads formatted input from stdin.
Declaration
Following is the declaration for scanf() function.
int scanf(const char *format, ...)
Example
The following example shows the usage of scanf() function.
#include <stdio.h>
int main () {
char str1[20], str2[30];
printf("Enter name: ");
scanf("%s", str1);
printf("Enter your website name: ");
scanf("%s", str2);
printf("Entered Name: %sn", str1);
printf("Entered Website:%s", str2);
return(0);
}
C)(i).printf:
printf function is used to print character stream of data on stdout console.
Syntax:
Example:
printf("hello geeksquiz");
fprintf:
fprintf is used to print the sting content in file but not on stdout console.
Example:
fprintf(fptr,"%d.%sn", i, str);
D)(ii). feof():
It checks ending of a file. It continuously return zero value until end of file not come and return non
zero value when end of file comes.
Syntax:
feof(file pointer);
Example:
FILE *fp;
if(feof(fp)==0)
{
printf(“not eof”); //when end of file not come
}
ferror():
It checks error in a file during reading process. If error comes ferror returns non zero value. It
continuously returns zero value during reading process.
Syntax:
ferror(file pointer);
Example:
if(ferror(fp)==0)
{
printf(“reading”);
}
if(ferror(fp)!=0)
{
printf(“error”);
}
3. Illustrate andexplainaC program to copy the contents of one file into
another.(13)
Explanation :
To copy a text from one file to another we have to follow following Steps :
Step 1 : Open Source File in Read Mode
fp1 = fopen("Sample.txt", "r");
Step 2 : OpenTarget File inWrite Mode
fp2 = fopen("Output.txt", "w");
Step 3 : Read Source File Character by Character
while (1) {
ch = fgetc(fp1);
if (ch == EOF)
break;
else
putc(ch, fp2);
}
 fgetc” will read character from source file.
 Check whether character is “End Character of File” or not , if yes then Terminate Loop
 “putc” will write Single Character on File Pointed by “fp2” pointer
Program:
#include <stdio.h>
#include <stdlib.h> // For exit()
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;
}
Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
Contents copied to b.txt
4. Explainthe read and write operations ona file withan suitable program.(13)
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that, fprint and
fscanf expects a pointer to the structure FILE.
Writingto a text file
Example 1: Write to a text file using fprintf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program takes a number from user and stores in the file program.txt.
Readingfroma text file
Example 2: Readfrom a text file using fscanf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:program.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
This program reads the integer present in the program.txt file and prints it onto the screen.
If you succesfully created the file from Example 1, running this program will get you the integer
you entered.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
Writingto a binaryfile
To write into a binary file, you need to use the function fwrite(). The functions 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.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Example 3: Writing to a binary file using fwrite()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:program.bin","wb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
In this program, you create a new file program.bin in the C drive.
We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main
function as num.
Now, inside the for loop, we store the value into the file using fwrite.
The first parameter takes the address of num and the second parameter takes the size of the
structure threeNum.
Since, we're only inserting one instance of num, the third parameter is 1. And, the last parameter
*fptr points to the file we're storing the data.
Finally, we close the file.
Readingfroma binaryfile
Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);
Example 4: Reading from a binary file using fread()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %dtn2: %dtn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr
into the structure num.
You'll get the same records you inserted in Example 3.
5. Describe the various functions usedinafile withexample.(13)
An C programming language offers many inbuilt functions for handling files. They are given
below.
File
handling functions
Description
fopen() fopen() functioncreatesanew file oropensanexistingfile.
fclose () fclose () functionclosesanopenedfile.
getw() getw() functionreadsan integerfromfile.
putw() putw() functionswritesanintegertofile.
fgetc() fgetc() functionreadsa character fromfile.
fputc() fputc() functionswrite acharacterto file.
fgets() fgets() functionreadsstringfroma file,one line atatime.
fputs() fputs() functionwritesstringtoa file.
feof () feof () functionfindsendof file.
fgetchar() fgetchar() functionreadsa character fromkeyboard.
fprintf () fprintf () functionwritesformatteddatatoa file.
fscanf () fscanf () functionreadsformatteddatafroma file.
fputchar()
fputchar () function writes a character onto the output screen from keyboard
input.
fseek() fseek() functionmovesfilepointerpositiontogivenlocation.
SEEK_SET SEEK_SET movesfile pointerpositiontothe beginningof the file.
SEEK_CUR SEEK_CUR movesfile pointerpositiontogivenlocation.
SEEK_END SEEK_END movesfile pointerpositiontothe endof file.
ftell () ftell () functiongivescurrentpositionof file pointer.
rewind() rewind() functionmovesfile pointerpositiontothe beginningof the file.
remove () remove () functiondeletesafile.
fflush() fflush() functionflushesafile.
6. Write aC Program to print names of all Files present inaDirectory.(13)
#include <stdio.h>
#include <dirent.h>
int main(void)
{
struct dirent *de; // Pointer for directory entry
// opendir() returns a pointer of DIR type.
DIR *dr = opendir(".");
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory" );
return 0;
}
while ((de = readdir(dr)) != NULL)
printf("%sn", de->d_name);
closedir(dr);
return 0;
}
Output:
All files and subdirectories
of current directory
DESCRIPTION
The type DIR, whichisdefinedinthe header <dirent.h>,representsadirectory stream,whichisan
orderedsequence of all the directoryentriesinaparticulardirectory.Directoryentriesrepresentfiles;
filesmaybe removedfromadirectoryor addedto a directoryasynchronouslytothe operationof
readdir().
The readdir() function returns a pointer to a structure representing the directory entry at the
current position in the directory stream specified by the argument dirp, and positions the
directory stream at the next entry. It returns a null pointer upon reaching the end of the directory
stream. The structure dirent defined by the <dirent.h> header describes a directory entry.
If entries for dot or dot-dot exist, one entry will be returned for dot and one entry will be returned
for dot-dot; otherwise they will not be returned.
The pointer returned by readdir() points to data which may be overwritten by another call to
readdir() on the same directory stream. This data is not overwritten by another call to readdir()
on a different directory stream.
If a file is removed from or added to the directory after the most recent call to opendir() or
rewinddir(), whether a subsequent call to readdir() returns an entry for that file is unspecified.
The readdir() function may buffer several directory entries per actual read operation; readdir()
marks for update the st_atime field of the directory each time the directory is actually read.
7. Write aC Program to readcontent of a File anddisplay it. (13)
#include <stdio.h>
#include <stdlib.h> // For exit() function
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^n]", c);
printf("Data from the file:n%s", c);
fclose(fptr);
return 0;
}
If the file program.txt is not found, this program prints error message.
If the file is found, the program saves the content of the file to a string c until 'n' newline is
encountered.
Suppose, the program.txt file contains following text.
C programming is awesome.
I love C programming.
How are you doing?
The output of the program will be:
Data from the file: C programming is awesome.
8. Write aC Program to print the contents of a File inreverse.(13)
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp1;
int cnt = 0;
int i = 0;
if( argc < 2 )
{
printf("Insufficient Arguments!!!n");
printf("Please use "program-name file-name" format.n");
return -1;
}
fp1 = fopen(argv[1],"r");
if( fp1 == NULL )
{
printf("n%s File can not be opened : n",argv[1]);
return -1;
}
//moves the file pointer to the end.
fseek(fp1,0,SEEK_END);
//get the position of file pointer.
cnt = ftell(fp1);
while( i < cnt )
{
i++;
fseek(fp1,-i,SEEK_END);
printf("%c",fgetc(fp1));
}
printf("n");
fclose(fp1);
return 0;
}
Actual file contents:
This is line1.
This is line2.
This is line3.
This is line4.
This is line5.
This is line6.
Terminal command: ./prg2 file1.txt
.6enil si sihT
.5enil si sihT
.4enil si sihT
.3enil si sihT
.2enil si sihT
.1enil si sihT
9.Write aC Program Transactionprocessing using randomaccess files.(13)
9. Write aC Program Transactionprocessing using randomaccess files.(16)
1 /* Fig. 11.16: fig11_16.c
2 This program reads a random access file sequentially,
3 updates data already written to the file, creates new
4 data to be placed in the file, and deletes data
5 already in the file. */
6 #include <stdio.h>
7
8 struct clientData {
9 int acctNum;
10 char lastName[ 15 ];
11 char firstName[ 10 ];
12 double balance;
13 };
14
15 int enterChoice( void );
16 void textFile( FILE * );
17 void updateRecord( FILE * );
18 void newRecord( FILE * );
19 void deleteRecord( FILE * );
20
21 int main()
22 {
23 FILE *cfPtr;
24 int choice;
25
26 if ( ( cfPtr = fopen( "credit.dat", "r+" ) ) == NULL )
27 printf( "File could not be opened.n" );
28 else {
29
30 while ( ( choice = enterChoice() ) != 5 ) {
31
32 switch ( choice ) {
33 case 1:
34 textFile( cfPtr );
35 break;
36 case 2:
37 updateRecord( cfPtr );
38 break;
39 case 3:
40 newRecord( cfPtr );
41 break;
42 case 4:
43 deleteRecord( cfPtr );
44 break;
45 }
46 }
47
48 fclose( cfPtr );
49 }
50
51 return 0;
52 }
53
54 void textFile( FILE *readPtr )
55 {
56 FILE *writePtr;
57 struct clientData client = { 0, "", "", 0.0 };
58
59 if ( ( writePtr = fopen( "accounts.txt", "w" ) ) == NULL )
60 printf( "File could not be opened.n" );
61 else {
62 rewind( readPtr );
63 fprintf( writePtr, "%-6s%-16s%-11s%10sn",
64 "Acct", "Last Name", "First Name","Balance" );
65
66 while ( !feof( readPtr ) ) {
67 fread( &client, sizeof( struct clientData ), 1,
68 readPtr );
69
70 if ( client.acctNum != 0 )
71 fprintf( writePtr, "%-6d%-16s%-11s%10.2fn",
72 client.acctNum, client.lastName,
73 client.firstName, client.balance );
74 }
75
76 fclose( writePtr );
77 }
78
79 }
80
81 void updateRecord( FILE *fPtr )
82 {
83 int account;
84 double transaction;
85 struct clientData client = { 0, "", "", 0.0 };
86
87 printf( "Enter account to update ( 1 - 100 ): " );
88 scanf( "%d", &account );
89 fseek( fPtr,
90 ( account - 1 ) * sizeof( struct clientData ),
91 SEEK_SET );
92 fread( &client, sizeof( struct clientData ), 1, fPtr );
93
94 if ( client.acctNum == 0 )
95 printf( "Acount #%d has no information.n", account );
96 else {
97 printf( "%-6d%-16s%-11s%10.2fnn",
98 client.acctNum, client.lastName,
99 client.firstName, client.balance );
100 printf( "Enter charge ( + ) or payment ( - ): " );
101 scanf( "%lf", &transaction );
102 client.balance += transaction;
103 printf( "%-6d%-16s%-11s%10.2fn",
104 client.acctNum, client.lastName,
105 client.firstName, client.balance );
106 fseek( fPtr,
107 ( account - 1 ) * sizeof( struct clientData ),
108 SEEK_SET );
109 fwrite( &client, sizeof( struct clientData ), 1,
110 fPtr );
111 }
112}
113
114void deleteRecord( FILE *fPtr )
115{
116 struct clientData client,
117 blankClient = { 0, "", "", 0 };
118 int accountNum;
119
120 printf( "Enter account number to "
121 "delete ( 1 - 100 ): " );
122 scanf( "%d", &accountNum );
123 fseek( fPtr,
124 ( accountNum - 1 ) * sizeof( struct clientData ),
125 SEEK_SET );
126 fread( &client, sizeof( struct clientData ), 1, fPtr );
127
128 if ( client.acctNum == 0 )
129 printf( "Account %d does not exist.n", accountNum );
130 else {
131 fseek( fPtr,
132 ( accountNum - 1 ) * sizeof( struct clientData ),
133 SEEK_SET );
134 fwrite( &blankClient,
135 sizeof( struct clientData ), 1, fPtr );
136 }
137}
138
139void newRecord( FILE *fPtr )
140{
141 struct clientData client = { 0, "", "", 0.0 };
142 int accountNum;
143 printf( "Enter new account number ( 1 - 100 ): " );
144 scanf( "%d", &accountNum );
145 fseek( fPtr,
146 ( accountNum - 1 ) * sizeof( struct clientData ),
147 SEEK_SET );
148 fread( &client, sizeof( struct clientData ), 1, fPtr );
149
150 if ( client.acctNum != 0 )
151 printf( "Account #%d already contains information.n",
152 client.acctNum );
153 else {
154 printf( "Enter lastname, firstname, balancen? " );
155 scanf( "%s%s%lf", &client.lastName, &client.firstName,
156 &client.balance );
157 client.acctNum = accountNum;
158 fseek( fPtr, ( client.acctNum - 1 ) *
159 sizeof( struct clientData ), SEEK_SET );
160 fwrite( &client,
161 sizeof( struct clientData ), 1, fPtr );
162 }
163}
164
165int enterChoice( void )
166{
167 int menuChoice;
168
169 printf( "nEnter your choicen"
170 "1 - store a formatted text file of acounts calledn"
171 " "accounts.txt" for printingn"
172 "2 - update an accountn"
173 "3 - add a new accountn"
174 "4 - delete an accountn"
175 "5 - end programn? " );
176 scanf( "%d", &menuChoice );
177 return menuChoice;
178}
10. Write a C program Finding average of numbers stored in sequentialaccess file.(13)
#include <stdio.h>
int main (int argc, const char * argv[])
{
FILE *input;
int term, sum,i=0;
char c=’y’;
float avg;
input = fopen("data.txt","w");
while(c==’y’)
{printf(“enter a no”);
Scanf(“%d”,&term);
fprintf(input,"%d",&term);
printf(“Continue y or n: “);
scanf(“%c”,c);
}
fclose(input);
sum = 0;
input = fopen("data.txt","r");
while(!feof(input))
{
fscanf(input,"%d",&term);
sum = sum + term;
i++;
}
fclose(input);
printf("The Avg of the numbers is %f.n",sum/i);
return 0;
}
11. Explain about command line argument with suitable example.(13)
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.
 parameters/argumentssuppliedtothe programwhenitisinvoked.Theyare usedto
control program fromoutside insteadof hard coding those valuesinside the code.
 In real time application,itwill happentopassargumentstothe mainprogram itself.
These argumentsare passedtothe main() functionwhile executing binary filefrom
commandline.
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.
ExampleforCommandLineArgument
#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("%st", 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.
12. Developa C Program tofind the number of lines ina text file.(13)
#include <stdio.h>
int main()
{
FILE *fileptr;
int count_lines = 0;
char filechar[40], chr;
printf("Enter file name: ");
scanf("%s", filechar);
fileptr = fopen(filechar, "r");
//extract character from file and store in chr
chr = getc(fileptr);
while (chr != EOF)
{
//Count whenever new line is encountered
if (chr == 'n')
{
count_lines = count_lines + 1;
}
//take next character from file.
chr = getc(fileptr);
}
fclose(fileptr); //close file.
printf("There are %d lines in %s in a filen", count_lines, filechar);
return 0;
}
13. Write a C Program to calculate the factorialof a number by using the command line
argument.(13)
The program to calculate the factorial of 10 was not very useful. Computer programs
typically work on a given set of input data to complete a task. We will extend the
example from the first lecture by introducing one of the ways to feed input to C
programs: command line arguments. The main() function in C could be declared as
int main(int argc, char** argv)
Note how this is different in factorial.c example we discussed last week. It takes two
parameters of type int and char** with variable names argc and argv. We will discuss
later what char** means. For now we will just focus on how to use these arguments to
read in input. The first parameter to the main() function specifies the number of
arguments on command line, the first of which is the name of the C program we are
running. The second parameter is an array that actually stores the command line
arguments. Here is an example: assume we converted our factorial.c program to take
any integer number to calculate the factorial.
Name this program : factorial2.c.
1 #include <stdio.h>
2 /*
3 * This program calculates the factorial of any given number.
4 */
5 int main(int agrc, char** argv)
6 {
7 /*
8 * Declarations.
9 */
10 int n;
11 double factorial;
12 int counter;
13
14 /*
15 * Initializations.
16 */
17 n = atoi(argv[1]);
18 factorial = 1.0;
19
20 /*
21 * Calculation of factorial.
22 */
23 for (counter = 1; counter <= n; counter = counter +1)
24 {
25 factorial = factorial * counter;
26 }
27
28 /*
29 * Print out the result.
30 */
31 printf("n!= %f n", factorial);
32 }
convert the command line argument “n” to an integer value by using standard library function called
atoi(char* s).
14. Write a C Program to generate Fibonacci series by using command line arguments.(13)
Hence a C Program computes first N fibonacci numbers using command line arguments.
Here is source code of the C Program to compute first N fibonacci numbers using command line
arguments.
#include <stdio.h>
/* Global Variable Declaration */
int first = 0;
int second = 1;
int third;
/* Function Prototype */
void rec_fibonacci(int);
void main(int argc, char *argv[])/* Command line Arguments*/
{
int number = atoi(argv[1]);
printf("%dt%d", first, second); /* To print first and second number
of fibonacci series */
rec_fibonacci(number);
printf("n");
}
/* Code to print fibonacci series using recursive function */
void rec_fibonacci(int num)
{
if (num == 2) /* To exit the function as the first two numbers are
already printed */
{
return;
}
third = first + second;
printf("t%d", third);
first = second;
second = third;
num--;
rec_fibonacci(num);
}
Output:
$ cc arg6.c
$ a.out 10
0 1 1 2 3 5 8 13 21 34
PART-C
1.(i) Write the case study of “How sequential accessfile isdifferfrom Random access file”.(10)
Sequential accessfile :
– Cannotbe modifiedwithoutthe riskof destroyingotherdata
– Fieldscanvary insize
• Differentrepresentationinfilesandscreenthaninternal representation
• Use fscanf to read fromthe file andfprintf towrite afile.
• Data read frombeginningtoend
• File positionpointer-Indicatesnumberof nextbyte tobe read/ written
•
You mightfindituseful toexamine yourworkloadtodeterminewhetheritaccessesdatarandomlyor
sequentially.If youfinddiskaccessispredominantlyrandom, youmightwanttopayparticularattention
to the activitiesbeingdone andmonitorforthe emergence of abottle neck..
Data in random access files:
– Unformatted (stored as "raw bytes" )
• All data of the same type (ints, for example) uses the same amount of
memory
• All records of the same type have a fixed length
• Data not human readable
• fread and fwrite functions used
– Access individual records without searching through other records
– Instant access to records in a file
– Data can be inserted without destroying other data
– Data previously stored can be updated or deleted without overwriting
• Implemented using fixed length records
– Sequential files do not have fixed length records
1 /* Fig. 11.3: fig11_03.c
2 Create a sequential file */
3 #include <stdio.h>
4
5 int main()
6 {
7 int account;
8 char name[ 30 ];
9 double balance;
10 FILE *cfPtr; /* cfPtr = clients.dat file pointer */
11
12 if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL )
13 printf( "File could not be openedn" );
14 else {
15 printf( "Enter the account, name, and balance.n" );
16 printf( "Enter EOF to end input.n" );
17 printf( "? " );
18 scanf( "%d%s%lf", &account, name, &balance );
19
20 while ( !feof( stdin ) ) {
21 fprintf( cfPtr, "%d %s %.2fn",
22 account, name, balance );
23 printf( "? " );
24 scanf( "%d%s%lf", &account, name, &balance );
25 }
26
27 fclose( cfPtr );
28 }
29
30 return 0;
31 }
1 /* Fig. 11.11: fig11_11.c
2 Creating a randomly accessed file sequentially */
3 #include <stdio.h>
4
5 struct clientData {
6 int acctNum;
7 char lastName[ 15 ];
8 char firstName[ 10 ];
9 double balance;
10 };
11
12 int main()
13 {
14 int i;
15 struct clientData blankClient = { 0, "", "", 0.0 };
16 FILE *cfPtr;
17
18 if ( ( cfPtr = fopen( "credit.dat", "w" ) ) == NULL )
19 printf( "File could not be opened.n" );
20 else {
21
22 for ( i = 1; i <= 100; i++ )
23 fwrite( &blankClient,
24 sizeof( struct clientData ), 1, cfPtr );
25
26 fclose( cfPtr );
27 }
28
29 return 0;
30 }
(ii) Write a C program to write all the membersof an array ofstructures to a file usingfwrite().Read
the array from the file anddisplay on the screen.(5)
#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
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: %snHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}
2. Summarize the various file openingmodeswiththeirdescriptions.(15)
File Modes
r Open a text file for reading.
w Create a text file for writing. If the file exists, it is overwritten.
a Open a text file in append mode. Text is added to the end of the
file.
rb Open a binary file for reading.
wb Create a binary file for writing. If the file exists, it is overwritten.
ab Open a binary file in append mode. Data is added to the end of
the file.
r+ Open a text file for reading and writing.
w+ Create a text file for reading and writing. If the file exists, it is
overwritten.
a+ Open a text file for reading and writing at the end.
r+b or
rb+
Open binary file for reading and writing.
w+b or
wb+
Create a binary file for reading and writing. If the file exists, it is
overwritten.
a+b or
ab+
Open a text file for reading and writing at the end.
3. Developa C Program to merge two files.(15)
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
printf("Enter name of first filen");
gets(file1);
printf("Enter name of second filen");
gets(file2);
printf("Enter name of file which will store contents of two filesn");
gets(file3);
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
if( fs1 == NULL || fs2 == NULL )
{
perror("Error ");
printf("Press any key to exit...n");
getch();
exit(EXIT_FAILURE);
}
ft = fopen(file3,"w");
if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fs1) ) != EOF )
fputc(ch,ft);
while( ( ch = fgetc(fs2) ) != EOF )
fputc(ch,ft);
printf("Two files were merged into %s file successfully.n",file3);
fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
}
4. Examine with example forthe functionsrequiredin binary file I/O operations.(15)
Binary File I/O uses fread and fwrite.
The declarations for each are similar:
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE
*a_file);
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements,
FILE *a_file);
Both of these functions deal with blocks of memories - usually arrays. Because they accept pointers,
you can also use these functions with other data structures; you can even write structs to a file or a
read struct into memory.
Example Program:
#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
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: %snHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}

More Related Content

What's hot

File handling in c
File handling in cFile handling in c
File handling in cmohit biswal
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10patcha535
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in CTushar B Kute
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in cMugdhaSharma11
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILESHarish Kamat
 
C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)leonard horobet-stoian
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYRajeshkumar Reddy
 
Programming in C
Programming in CProgramming in C
Programming in Csujathavvv
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CMahendra Yadav
 
Read write program
Read write programRead write program
Read write programAMI AMITO
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-duttAnil Dutt
 

What's hot (19)

File handling in c
File handling in cFile handling in c
File handling in c
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File handling in C
File handling in CFile handling in C
File handling in C
 
7.0 files and c input
7.0 files and c input7.0 files and c input
7.0 files and c input
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
Unit 8
Unit 8Unit 8
Unit 8
 
File mangement
File mangementFile mangement
File mangement
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in c
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)
 
Python-files
Python-filesPython-files
Python-files
 
Unit v
Unit vUnit v
Unit v
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
Programming in C
Programming in CProgramming in C
Programming in C
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
Read write program
Read write programRead write program
Read write program
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 

Similar to FILE HANDLING IN C

File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfsangeeta borde
 
ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfMalligaarjunanN
 
File Management in C
File Management in CFile Management in C
File Management in CPaurav Shah
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CAshim Lamichhane
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)Kamlesh Nishad
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
C programming session 08
C programming session 08C programming session 08
C programming session 08Dushmanta Nath
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C ProgrammingRavindraSalunke3
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
 
file handling1
file handling1file handling1
file handling1student
 

Similar to FILE HANDLING IN C (20)

C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Unit5
Unit5Unit5
Unit5
 
Handout#01
Handout#01Handout#01
Handout#01
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
File management
File managementFile management
File management
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
File Organization
File OrganizationFile Organization
File Organization
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
file handling1
file handling1file handling1
file handling1
 

More from Sowri Rajan

More from Sowri Rajan (11)

Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Unitii string
Unitii stringUnitii string
Unitii string
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Uniti classnotes
Uniti classnotesUniti classnotes
Uniti classnotes
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 

Recently uploaded

Roadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMRoadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMroute66connected
 
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in Noida | Delhi
FULL ENJOY - 9953040155 Call Girls in Noida | DelhiFULL ENJOY - 9953040155 Call Girls in Noida | Delhi
FULL ENJOY - 9953040155 Call Girls in Noida | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiMalviyaNagarCallGirl
 
Benjamin Portfolio Process Work Slideshow
Benjamin Portfolio Process Work SlideshowBenjamin Portfolio Process Work Slideshow
Benjamin Portfolio Process Work Slideshowssuser971f6c
 
SHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
SHIVNA SAHITYIKI APRIL JUNE 2024 MagazineSHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
SHIVNA SAHITYIKI APRIL JUNE 2024 MagazineShivna Prakashan
 
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857delhimodel235
 
Olivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxOlivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxLauraFagan6
 
Bare And Wild Creation, Curio Shop, Tucumcari NM
Bare And Wild Creation, Curio Shop, Tucumcari NMBare And Wild Creation, Curio Shop, Tucumcari NM
Bare And Wild Creation, Curio Shop, Tucumcari NMroute66connected
 
Retail Store Scavanger Hunt - Foundation College Park
Retail Store Scavanger Hunt - Foundation College ParkRetail Store Scavanger Hunt - Foundation College Park
Retail Store Scavanger Hunt - Foundation College Parkjosebenzaquen
 
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call GirlsJagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Availabledollysharma2066
 
Russian Call Girls Delhi NCR 9999965857 Call or WhatsApp Anytime
Russian Call Girls Delhi NCR 9999965857 Call or WhatsApp AnytimeRussian Call Girls Delhi NCR 9999965857 Call or WhatsApp Anytime
Russian Call Girls Delhi NCR 9999965857 Call or WhatsApp AnytimeKomal Khan
 
FULL ENJOY - 9953040155 Call Girls in Karol Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Karol Bagh | DelhiFULL ENJOY - 9953040155 Call Girls in Karol Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Karol Bagh | DelhiMalviyaNagarCallGirl
 
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...dajasot375
 
Burari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call GirlsBurari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Triangle Vinyl Record Store, Clermont Florida
Triangle Vinyl Record Store, Clermont FloridaTriangle Vinyl Record Store, Clermont Florida
Triangle Vinyl Record Store, Clermont FloridaGabrielaMiletti
 
Call Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceCall Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceAyesha Khan
 
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiMalviyaNagarCallGirl
 
Call Girl Service in Karachi +923081633338 Karachi Call Girls
Call Girl Service in Karachi +923081633338 Karachi Call GirlsCall Girl Service in Karachi +923081633338 Karachi Call Girls
Call Girl Service in Karachi +923081633338 Karachi Call GirlsAyesha Khan
 

Recently uploaded (20)

Roadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMRoadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NM
 
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
 
FULL ENJOY - 9953040155 Call Girls in Noida | Delhi
FULL ENJOY - 9953040155 Call Girls in Noida | DelhiFULL ENJOY - 9953040155 Call Girls in Noida | Delhi
FULL ENJOY - 9953040155 Call Girls in Noida | Delhi
 
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
 
Benjamin Portfolio Process Work Slideshow
Benjamin Portfolio Process Work SlideshowBenjamin Portfolio Process Work Slideshow
Benjamin Portfolio Process Work Slideshow
 
SHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
SHIVNA SAHITYIKI APRIL JUNE 2024 MagazineSHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
SHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
 
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
 
Olivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxOlivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptx
 
Bare And Wild Creation, Curio Shop, Tucumcari NM
Bare And Wild Creation, Curio Shop, Tucumcari NMBare And Wild Creation, Curio Shop, Tucumcari NM
Bare And Wild Creation, Curio Shop, Tucumcari NM
 
Retail Store Scavanger Hunt - Foundation College Park
Retail Store Scavanger Hunt - Foundation College ParkRetail Store Scavanger Hunt - Foundation College Park
Retail Store Scavanger Hunt - Foundation College Park
 
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call GirlsJagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
 
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
 
Russian Call Girls Delhi NCR 9999965857 Call or WhatsApp Anytime
Russian Call Girls Delhi NCR 9999965857 Call or WhatsApp AnytimeRussian Call Girls Delhi NCR 9999965857 Call or WhatsApp Anytime
Russian Call Girls Delhi NCR 9999965857 Call or WhatsApp Anytime
 
FULL ENJOY - 9953040155 Call Girls in Karol Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Karol Bagh | DelhiFULL ENJOY - 9953040155 Call Girls in Karol Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Karol Bagh | Delhi
 
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
 
Burari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call GirlsBurari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call Girls
 
Triangle Vinyl Record Store, Clermont Florida
Triangle Vinyl Record Store, Clermont FloridaTriangle Vinyl Record Store, Clermont Florida
Triangle Vinyl Record Store, Clermont Florida
 
Call Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceCall Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl Service
 
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
 
Call Girl Service in Karachi +923081633338 Karachi Call Girls
Call Girl Service in Karachi +923081633338 Karachi Call GirlsCall Girl Service in Karachi +923081633338 Karachi Call Girls
Call Girl Service in Karachi +923081633338 Karachi Call Girls
 

FILE HANDLING IN C

  • 1. Unit 5 Part –A 1. Define file.  A file represents a sequence of bytes on the disk where a group of related data is stored. (Or)  A file is a collection of records. 2. Mentiondifferenttype of file accessing.  SequentialaccessandRandomaccess When dealing with files, there are two types of files they are: 1. Text files and 2. Binary files. 3. DistinguishbetweenSequentialaccessandRandomaccess. Sequential files are generally used in cases where the program processes the data in a sequential fashion – i.e. counting words in a text file True random access file handling, however, only accesses the file at the point at which the data should be read or written, rather than having to process it sequentially. 4. What ismeantby commandline argument.?Give anexample.  Command-line arguments are given after the name of the program in command-line shell of Operating Systems. To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. int main(int argc, char *argv[]) { /* ... */ } 5. List outthe variousfile handlingfunction. There are many functions in C library to open, read, write, search and close file. A list of file functions are given below: Function Description fopen() opens new or existing file fprintf() write data into file fscanf() reads data from file
  • 2. fputc() writes a character into file fgetc() reads a character from file fclose() closes the file fseek() sets the file pointer to given position fputw() writes an integer to file fgetw() reads an integer from file ftell() returns current position rewind() sets the file pointer to the beginning of the file 6. Compare fseek()andftell() function. fseek() This function is used for seeking the pointer position in the file at the specified byte. Syntax: fseek (file pointer, displacement, pointer position); Where file pointer ---- It is the pointer which points to the file. 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. This sets the pointer position in the file. Value pointer position 0 Beginning of file. 1 Current position 2 End of file 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. 7. How to create a file inC ? File canbe createdas follows: o Declare a file pointer variable.
  • 3. o Open a file using fopen() function. o Process the file using the suitable function. o Close the file using fclose() function Example: FILE *fp = NULL; fp = fopen("textFile.txt" ,"w"); 8. Why filesare needed?  Filesare neededforthe computerthatstoresdata,information,settings,orcommandsused witha computerprogram.  When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates.  If you have to enter a large number of data, it will take a lot of time to enter them all. However, if you have a file containing all the data, you can easily access the contents of the file using few commands in C.  You can easily move your data from one computer to another without any changes. 9. How to readand write the file.?  For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a pointer to the structure FILE.  r,w,a,w+,r+,a+ modes used for read and write operations. 10. Compare the termsField,RecordandFile. Field: A single piece of information about an object. If the object were an Employee, a field would be Firstname, Lastname, or City or State. Record: A collection of fields. In an Employee file, there would be one record for John Smith, another record for Mary Jones, and another record for Al Newman. File: A collection of bytes. The bytes may represent numbers or characters. In business systems, files usually consist of collections of records. 11. Examine the following:‐ (i) getc() andgetchar() getc(): It reads a single character from a given input stream and returns the corresponding integer value (typically ASCII value of read character) on success. It returns EOF on failure. Syntax: int getc(FILE *stream);
  • 4. getchar(): The difference between getc() and getchar() is getc() can read from any input stream, but getchar() reads from standard input. So getchar() is equivalent to getc(stdin). Syntax: int getchar(void); (ii)scanf andfscanf() scanf() : The C library function int scanf (const char *format, …) reads formatted input from stdin. Type specifiers that can be used in scanf: %c — Character %d — Signed integer %f — Floating point %s — String fscanf() : fscanf() is used to read formatted input from a file. 12. Distinguishbetweenfollowing:‐ (i).printf () andfprintf() ii).feof() andferror() (i).printf: printf function is used to print character stream of data on stdout console. Syntax: Example: printf("hello geeksquiz"); fprintf: fprintf is used to print the sting content in file but not on stdout console. Example: fprintf(fptr,"%d.%sn", i, str); (ii). feof(): It checks ending of a file. It continuously return zero value until end of file not come and return non zero value when end of file comes. Syntax: feof(file pointer);
  • 5. Example: FILE *fp; if(feof(fp)==0) { printf(“not eof”); //when end of file not come } ferror(): It checks error in a file during reading process. If error comes ferror returns non zero value. It continuously returns zero value during reading process. Syntax: ferror(file pointer); Example: if(ferror(fp)==0) { printf(“reading”); } if(ferror(fp)!=0) { printf(“error”); } 13. Whichof the followingoperationscanbe performedonthe file "NOTES.TXT"usingthe below code? FILE *fp; fp = fopen("NOTES.TXT","r+"); Ans.Open an existing file for update (reading and writing). 14. Identifythe differenttypesof file. A file canbe of twotypes • Textfile • Binaryfile Text files:A textfilecanbe a streamof characters that a computercan processsequentially.A text streamin C isa special kindof file.Itisnotonlyprocessedsequentiallybutonlyinforwarddirection. A binary file isdifferenttoatextfile.Itisa collectionof bytes.InCProgrammingLanguage a byte and a character are equivalent.Nospecialprocessingof the dataoccurs and eachbyte of data istransferredto or from the diskunprocessed. 15. Identifythe difference betweenAppendandWrite Mode. Write (w) mode and Append(a) mode,while openingafile are almostthe same.Bothare usedto write ina file.Inboththe modes,newfileiscreatedif itdoesnotalreadyexist.The onlydifference theyhave
  • 6. is, whenyouopena file inthe write mode,the file isreset,resultingindeletionof anydataalready presentinthe file.Whileinappendmode thiswill nothappen.Appendmode isusedtoappendoradd data to the existingdataof file,if any.Hence,whenyouopenafile inAppend(a) mode,the cursoris positionedatthe endof the presentdatainthe file. 16. What isthe use of rewind() functions. The rewind function sets the file position to the beginning of the file for the stream pointed to by stream. It also clears the error and end-of-file indicators for stream. Syntax The syntax for the rewind function in the C Language is: void rewind(FILE *stream); 17. Write a C Program to findthe Size of a File. Here is source code of the C Program to find the size of file using file handling function. 1. #include <stdio.h> 2. void main(int argc, char **argv) 3. { 4. FILE *fp; 5. char ch; 6. int size = 0; 7. fp = fopen(argv[1], "r"); 8. if (fp == NULL) 9. printf("nFile unable to open "); 10. else 11. printf("nFile opened "); 12. fseek(fp, 0, 2); /* file pointer at the end of file */ 13. size = ftell(fp); /* take a position of file pointer */ 14. printf("The size of given file is : %dn", size); 15. fclose(fp); 16. }
  • 7. 18. Write the Stepsfor ProcessingaFile 19. Write a code inC to definingandopeningaFile. #include<stdio.h> int main() { FILE *fp; char ch; fp = fopen("INPUT.txt","r") // Open file in Read mode fclose(fp); // Close File after Reading return(0); } 20. What doesargv andargc indicate incommand-line arguments? argv(ARGument Vector) is array of character pointers listing all the arguments. argc is the number of command line arguments Part-B 1. Describe the followingfile manipulationfunctions withexamples.(13)
  • 8. i) rename().(3) ii) remove().(5) iii) fflush().(5) i) rename()’ function can be called to change the name of a file from oldname to newname. If the file with newname is already existing while ‘rename()’ was called, behaviour is implementation defined. Both the functions return ZERO when succeed and non-zero value when they fail. If ‘rename()’ fails, file with original name is yet accessible. For example, for an existing file “hello.txt”, rename("hello.txt", "byebye.txt"); They are prototypedbelow: int rename(char const *oldname, char const *newname); ii) remove()’ functioncanbe usedtoexplicitlyclose/deleteafile specifiedbyargument.If the specified file isopenwhile remove() wascalled,behaviourisimplementationdefined. For example, for an existing file “hello.txt”, remove("hello.txt"); Theyare prototypedbelow: int remove(char const *filename); iii) fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output buffer and move the buffered data to console (in case of stdout) or disk (in case of file output stream). Below is its syntax. fflush(FILE *ostream); Example: #include <stdio.h> #include<stdlib.h> int main() { char str[20]; int i; for (i=0; i<2; i++) { scanf("%[^n]s", str); printf("%sn", str); // fflush(stdin);
  • 9. } return 0; } Input: geeks geeksforgeeks Output: geeks geeksforgeeks 2. Distinguishbetweenthe followingfunctions.(13) a) getc() andgetchar().(3) b) scanf() and fscanf().(3) c) printf() andfprintf().(3) d) feof() andferror().(4) a) getc(): It reads a single character from a given input stream and returns the corresponding integer value (typically ASCII value of read character) on success. It returns EOF on failure. Syntax: int getc(FILE *stream); Example: // Example for getc() in C #include <stdio.h> int main() { printf("%c", getc(stdin)); return(0); } Output: g getchar(): The difference between getc() and getchar() is getc() can read from any input stream, but getchar() reads from standard input. So getchar() is equivalent to getc(stdin).
  • 10. Syntax: int getchar(void); Example: // Example for getchar() in C #include <stdio.h> int main() { printf("%c", getchar()); return 0; } b) The fscanf() function is used to read mixed type form the file. Syntaxof fscanf()function fscanf(FILE *fp,"format-string",var-list); The fscanf() function is similar to scanf() function except the first argument which is a file pointer that specifies the file to be read. Exampleoffscanf()function #include<stdio.h> void main() { FILE *fp; char ch; fp = fopen("file.txt","r"); //Statement 1 if(fp == NULL) { Printf ("nCan't open file or file doesn't exist."); exit(0); } printf("nData in file...n"); while((fscanf(fp,"%d%s%f",&roll,name,&marks))!=EOF) //Statement 2 printf("n%dt%st%f",roll,name,marks); fclose(fp); } Output : Data in file... 1 Kumar 78.53 2 Sumit 89.62
  • 11. int scanf(const char *format, ...) reads formatted input from stdin. Declaration Following is the declaration for scanf() function. int scanf(const char *format, ...) Example The following example shows the usage of scanf() function. #include <stdio.h> int main () { char str1[20], str2[30]; printf("Enter name: "); scanf("%s", str1); printf("Enter your website name: "); scanf("%s", str2); printf("Entered Name: %sn", str1); printf("Entered Website:%s", str2); return(0); } C)(i).printf: printf function is used to print character stream of data on stdout console. Syntax: Example: printf("hello geeksquiz"); fprintf: fprintf is used to print the sting content in file but not on stdout console. Example: fprintf(fptr,"%d.%sn", i, str); D)(ii). feof(): It checks ending of a file. It continuously return zero value until end of file not come and return non zero value when end of file comes. Syntax: feof(file pointer);
  • 12. Example: FILE *fp; if(feof(fp)==0) { printf(“not eof”); //when end of file not come } ferror(): It checks error in a file during reading process. If error comes ferror returns non zero value. It continuously returns zero value during reading process. Syntax: ferror(file pointer); Example: if(ferror(fp)==0) { printf(“reading”); } if(ferror(fp)!=0) { printf(“error”); } 3. Illustrate andexplainaC program to copy the contents of one file into another.(13) Explanation : To copy a text from one file to another we have to follow following Steps : Step 1 : Open Source File in Read Mode fp1 = fopen("Sample.txt", "r"); Step 2 : OpenTarget File inWrite Mode fp2 = fopen("Output.txt", "w"); Step 3 : Read Source File Character by Character while (1) { ch = fgetc(fp1); if (ch == EOF) break; else putc(ch, fp2); }  fgetc” will read character from source file.
  • 13.  Check whether character is “End Character of File” or not , if yes then Terminate Loop  “putc” will write Single Character on File Pointed by “fp2” pointer Program: #include <stdio.h> #include <stdlib.h> // For exit() 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; } Output: Enter the filename to open for reading
  • 14. a.txt Enter the filename to open for writing b.txt Contents copied to b.txt 4. Explainthe read and write operations ona file withan suitable program.(13) For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a pointer to the structure FILE. Writingto a text file Example 1: Write to a text file using fprintf() #include <stdio.h> int main() { int num; FILE *fptr; fptr = fopen("C:program.txt","w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; } This program takes a number from user and stores in the file program.txt. Readingfroma text file Example 2: Readfrom a text file using fscanf() #include <stdio.h> int main() { int num; FILE *fptr; if ((fptr = fopen("C:program.txt","r")) == NULL){
  • 15. printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; } This program reads the integer present in the program.txt file and prints it onto the screen. If you succesfully created the file from Example 1, running this program will get you the integer you entered. Other functions like fgetchar(), fputc() etc. can be used in similar way. Reading and writing to a binary file Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files. Writingto a binaryfile To write into a binary file, you need to use the function fwrite(). The functions 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. fwrite(address_data,size_data,numbers_data,pointer_to_file); Example 3: Writing to a binary file using fwrite() #include <stdio.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:program.bin","wb")) == NULL){ printf("Error! opening file");
  • 16. // Program exits if the file pointer returns NULL. exit(1); } for(n = 1; n < 5; ++n) { num.n1 = n; num.n2 = 5n; num.n3 = 5n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } fclose(fptr); return 0; } In this program, you create a new file program.bin in the C drive. We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main function as num. Now, inside the for loop, we store the value into the file using fwrite. The first parameter takes the address of num and the second parameter takes the size of the structure threeNum. Since, we're only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the data. Finally, we close the file. Readingfroma binaryfile Function fread() also take 4 arguments similar to fwrite() function as above. fread(address_data,size_data,numbers_data,pointer_to_file); Example 4: Reading from a binary file using fread() #include <stdio.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num;
  • 17. FILE *fptr; if ((fptr = fopen("C:program.bin","rb")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } for(n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %dtn2: %dtn3: %d", num.n1, num.n2, num.n3); } fclose(fptr); return 0; } In this program, you read the same file program.bin and loop through the records one by one. In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the structure num. You'll get the same records you inserted in Example 3. 5. Describe the various functions usedinafile withexample.(13) An C programming language offers many inbuilt functions for handling files. They are given below. File handling functions Description fopen() fopen() functioncreatesanew file oropensanexistingfile. fclose () fclose () functionclosesanopenedfile. getw() getw() functionreadsan integerfromfile. putw() putw() functionswritesanintegertofile. fgetc() fgetc() functionreadsa character fromfile. fputc() fputc() functionswrite acharacterto file.
  • 18. fgets() fgets() functionreadsstringfroma file,one line atatime. fputs() fputs() functionwritesstringtoa file. feof () feof () functionfindsendof file. fgetchar() fgetchar() functionreadsa character fromkeyboard. fprintf () fprintf () functionwritesformatteddatatoa file. fscanf () fscanf () functionreadsformatteddatafroma file. fputchar() fputchar () function writes a character onto the output screen from keyboard input. fseek() fseek() functionmovesfilepointerpositiontogivenlocation. SEEK_SET SEEK_SET movesfile pointerpositiontothe beginningof the file. SEEK_CUR SEEK_CUR movesfile pointerpositiontogivenlocation. SEEK_END SEEK_END movesfile pointerpositiontothe endof file. ftell () ftell () functiongivescurrentpositionof file pointer. rewind() rewind() functionmovesfile pointerpositiontothe beginningof the file. remove () remove () functiondeletesafile. fflush() fflush() functionflushesafile. 6. Write aC Program to print names of all Files present inaDirectory.(13) #include <stdio.h> #include <dirent.h> int main(void) { struct dirent *de; // Pointer for directory entry
  • 19. // opendir() returns a pointer of DIR type. DIR *dr = opendir("."); if (dr == NULL) // opendir returns NULL if couldn't open directory { printf("Could not open current directory" ); return 0; } while ((de = readdir(dr)) != NULL) printf("%sn", de->d_name); closedir(dr); return 0; } Output: All files and subdirectories of current directory DESCRIPTION The type DIR, whichisdefinedinthe header <dirent.h>,representsadirectory stream,whichisan orderedsequence of all the directoryentriesinaparticulardirectory.Directoryentriesrepresentfiles; filesmaybe removedfromadirectoryor addedto a directoryasynchronouslytothe operationof readdir(). The readdir() function returns a pointer to a structure representing the directory entry at the current position in the directory stream specified by the argument dirp, and positions the directory stream at the next entry. It returns a null pointer upon reaching the end of the directory stream. The structure dirent defined by the <dirent.h> header describes a directory entry. If entries for dot or dot-dot exist, one entry will be returned for dot and one entry will be returned for dot-dot; otherwise they will not be returned. The pointer returned by readdir() points to data which may be overwritten by another call to readdir() on the same directory stream. This data is not overwritten by another call to readdir() on a different directory stream.
  • 20. If a file is removed from or added to the directory after the most recent call to opendir() or rewinddir(), whether a subsequent call to readdir() returns an entry for that file is unspecified. The readdir() function may buffer several directory entries per actual read operation; readdir() marks for update the st_atime field of the directory each time the directory is actually read. 7. Write aC Program to readcontent of a File anddisplay it. (13) #include <stdio.h> #include <stdlib.h> // For exit() function int main() { char c[1000]; FILE *fptr; if ((fptr = fopen("program.txt", "r")) == NULL) { printf("Error! opening file"); // Program exits if file pointer returns NULL. exit(1); } // reads text until newline fscanf(fptr,"%[^n]", c); printf("Data from the file:n%s", c); fclose(fptr); return 0; } If the file program.txt is not found, this program prints error message. If the file is found, the program saves the content of the file to a string c until 'n' newline is encountered. Suppose, the program.txt file contains following text. C programming is awesome. I love C programming. How are you doing? The output of the program will be: Data from the file: C programming is awesome. 8. Write aC Program to print the contents of a File inreverse.(13)
  • 21. #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { FILE *fp1; int cnt = 0; int i = 0; if( argc < 2 ) { printf("Insufficient Arguments!!!n"); printf("Please use "program-name file-name" format.n"); return -1; } fp1 = fopen(argv[1],"r"); if( fp1 == NULL ) { printf("n%s File can not be opened : n",argv[1]); return -1; } //moves the file pointer to the end. fseek(fp1,0,SEEK_END); //get the position of file pointer. cnt = ftell(fp1); while( i < cnt ) { i++; fseek(fp1,-i,SEEK_END); printf("%c",fgetc(fp1)); } printf("n"); fclose(fp1); return 0; } Actual file contents: This is line1. This is line2. This is line3. This is line4. This is line5. This is line6. Terminal command: ./prg2 file1.txt .6enil si sihT .5enil si sihT .4enil si sihT .3enil si sihT .2enil si sihT .1enil si sihT 9.Write aC Program Transactionprocessing using randomaccess files.(13)
  • 22. 9. Write aC Program Transactionprocessing using randomaccess files.(16) 1 /* Fig. 11.16: fig11_16.c 2 This program reads a random access file sequentially, 3 updates data already written to the file, creates new 4 data to be placed in the file, and deletes data 5 already in the file. */ 6 #include <stdio.h> 7 8 struct clientData { 9 int acctNum; 10 char lastName[ 15 ]; 11 char firstName[ 10 ]; 12 double balance; 13 }; 14 15 int enterChoice( void ); 16 void textFile( FILE * ); 17 void updateRecord( FILE * ); 18 void newRecord( FILE * ); 19 void deleteRecord( FILE * ); 20 21 int main() 22 { 23 FILE *cfPtr; 24 int choice; 25 26 if ( ( cfPtr = fopen( "credit.dat", "r+" ) ) == NULL ) 27 printf( "File could not be opened.n" ); 28 else { 29 30 while ( ( choice = enterChoice() ) != 5 ) { 31 32 switch ( choice ) {
  • 23. 33 case 1: 34 textFile( cfPtr ); 35 break; 36 case 2: 37 updateRecord( cfPtr ); 38 break; 39 case 3: 40 newRecord( cfPtr ); 41 break; 42 case 4: 43 deleteRecord( cfPtr ); 44 break; 45 } 46 } 47 48 fclose( cfPtr ); 49 } 50 51 return 0; 52 } 53 54 void textFile( FILE *readPtr ) 55 { 56 FILE *writePtr; 57 struct clientData client = { 0, "", "", 0.0 }; 58 59 if ( ( writePtr = fopen( "accounts.txt", "w" ) ) == NULL ) 60 printf( "File could not be opened.n" ); 61 else { 62 rewind( readPtr ); 63 fprintf( writePtr, "%-6s%-16s%-11s%10sn", 64 "Acct", "Last Name", "First Name","Balance" );
  • 24. 65 66 while ( !feof( readPtr ) ) { 67 fread( &client, sizeof( struct clientData ), 1, 68 readPtr ); 69 70 if ( client.acctNum != 0 ) 71 fprintf( writePtr, "%-6d%-16s%-11s%10.2fn", 72 client.acctNum, client.lastName, 73 client.firstName, client.balance ); 74 } 75 76 fclose( writePtr ); 77 } 78 79 } 80 81 void updateRecord( FILE *fPtr ) 82 { 83 int account; 84 double transaction; 85 struct clientData client = { 0, "", "", 0.0 }; 86 87 printf( "Enter account to update ( 1 - 100 ): " ); 88 scanf( "%d", &account ); 89 fseek( fPtr, 90 ( account - 1 ) * sizeof( struct clientData ), 91 SEEK_SET ); 92 fread( &client, sizeof( struct clientData ), 1, fPtr ); 93 94 if ( client.acctNum == 0 ) 95 printf( "Acount #%d has no information.n", account ); 96 else {
  • 25. 97 printf( "%-6d%-16s%-11s%10.2fnn", 98 client.acctNum, client.lastName, 99 client.firstName, client.balance ); 100 printf( "Enter charge ( + ) or payment ( - ): " ); 101 scanf( "%lf", &transaction ); 102 client.balance += transaction; 103 printf( "%-6d%-16s%-11s%10.2fn", 104 client.acctNum, client.lastName, 105 client.firstName, client.balance ); 106 fseek( fPtr, 107 ( account - 1 ) * sizeof( struct clientData ), 108 SEEK_SET ); 109 fwrite( &client, sizeof( struct clientData ), 1, 110 fPtr ); 111 } 112} 113 114void deleteRecord( FILE *fPtr ) 115{ 116 struct clientData client, 117 blankClient = { 0, "", "", 0 }; 118 int accountNum; 119 120 printf( "Enter account number to " 121 "delete ( 1 - 100 ): " ); 122 scanf( "%d", &accountNum ); 123 fseek( fPtr, 124 ( accountNum - 1 ) * sizeof( struct clientData ), 125 SEEK_SET ); 126 fread( &client, sizeof( struct clientData ), 1, fPtr );
  • 26. 127 128 if ( client.acctNum == 0 ) 129 printf( "Account %d does not exist.n", accountNum ); 130 else { 131 fseek( fPtr, 132 ( accountNum - 1 ) * sizeof( struct clientData ), 133 SEEK_SET ); 134 fwrite( &blankClient, 135 sizeof( struct clientData ), 1, fPtr ); 136 } 137} 138 139void newRecord( FILE *fPtr ) 140{ 141 struct clientData client = { 0, "", "", 0.0 }; 142 int accountNum; 143 printf( "Enter new account number ( 1 - 100 ): " ); 144 scanf( "%d", &accountNum ); 145 fseek( fPtr, 146 ( accountNum - 1 ) * sizeof( struct clientData ), 147 SEEK_SET ); 148 fread( &client, sizeof( struct clientData ), 1, fPtr ); 149 150 if ( client.acctNum != 0 ) 151 printf( "Account #%d already contains information.n", 152 client.acctNum ); 153 else { 154 printf( "Enter lastname, firstname, balancen? " ); 155 scanf( "%s%s%lf", &client.lastName, &client.firstName, 156 &client.balance );
  • 27. 157 client.acctNum = accountNum; 158 fseek( fPtr, ( client.acctNum - 1 ) * 159 sizeof( struct clientData ), SEEK_SET ); 160 fwrite( &client, 161 sizeof( struct clientData ), 1, fPtr ); 162 } 163} 164 165int enterChoice( void ) 166{ 167 int menuChoice; 168 169 printf( "nEnter your choicen" 170 "1 - store a formatted text file of acounts calledn" 171 " "accounts.txt" for printingn" 172 "2 - update an accountn" 173 "3 - add a new accountn" 174 "4 - delete an accountn" 175 "5 - end programn? " ); 176 scanf( "%d", &menuChoice ); 177 return menuChoice; 178}
  • 28. 10. Write a C program Finding average of numbers stored in sequentialaccess file.(13) #include <stdio.h> int main (int argc, const char * argv[]) { FILE *input; int term, sum,i=0; char c=’y’; float avg; input = fopen("data.txt","w"); while(c==’y’) {printf(“enter a no”); Scanf(“%d”,&term); fprintf(input,"%d",&term); printf(“Continue y or n: “); scanf(“%c”,c); } fclose(input); sum = 0; input = fopen("data.txt","r"); while(!feof(input)) { fscanf(input,"%d",&term); sum = sum + term; i++; } fclose(input); printf("The Avg of the numbers is %f.n",sum/i); return 0; } 11. Explain about command line argument with suitable example.(13) 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.  parameters/argumentssuppliedtothe programwhenitisinvoked.Theyare usedto control program fromoutside insteadof hard coding those valuesinside the code.  In real time application,itwill happentopassargumentstothe mainprogram itself. These argumentsare passedtothe main() functionwhile executing binary filefrom commandline.
  • 29. 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. ExampleforCommandLineArgument #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("%st", 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. 12. Developa C Program tofind the number of lines ina text file.(13) #include <stdio.h> int main() { FILE *fileptr; int count_lines = 0; char filechar[40], chr; printf("Enter file name: "); scanf("%s", filechar); fileptr = fopen(filechar, "r");
  • 30. //extract character from file and store in chr chr = getc(fileptr); while (chr != EOF) { //Count whenever new line is encountered if (chr == 'n') { count_lines = count_lines + 1; } //take next character from file. chr = getc(fileptr); } fclose(fileptr); //close file. printf("There are %d lines in %s in a filen", count_lines, filechar); return 0; } 13. Write a C Program to calculate the factorialof a number by using the command line argument.(13) The program to calculate the factorial of 10 was not very useful. Computer programs typically work on a given set of input data to complete a task. We will extend the example from the first lecture by introducing one of the ways to feed input to C programs: command line arguments. The main() function in C could be declared as int main(int argc, char** argv) Note how this is different in factorial.c example we discussed last week. It takes two parameters of type int and char** with variable names argc and argv. We will discuss later what char** means. For now we will just focus on how to use these arguments to read in input. The first parameter to the main() function specifies the number of arguments on command line, the first of which is the name of the C program we are running. The second parameter is an array that actually stores the command line arguments. Here is an example: assume we converted our factorial.c program to take any integer number to calculate the factorial. Name this program : factorial2.c. 1 #include <stdio.h> 2 /* 3 * This program calculates the factorial of any given number.
  • 31. 4 */ 5 int main(int agrc, char** argv) 6 { 7 /* 8 * Declarations. 9 */ 10 int n; 11 double factorial; 12 int counter; 13 14 /* 15 * Initializations. 16 */ 17 n = atoi(argv[1]); 18 factorial = 1.0; 19 20 /* 21 * Calculation of factorial. 22 */ 23 for (counter = 1; counter <= n; counter = counter +1) 24 { 25 factorial = factorial * counter; 26 } 27 28 /* 29 * Print out the result. 30 */ 31 printf("n!= %f n", factorial); 32 } convert the command line argument “n” to an integer value by using standard library function called atoi(char* s).
  • 32. 14. Write a C Program to generate Fibonacci series by using command line arguments.(13) Hence a C Program computes first N fibonacci numbers using command line arguments. Here is source code of the C Program to compute first N fibonacci numbers using command line arguments. #include <stdio.h> /* Global Variable Declaration */ int first = 0; int second = 1; int third; /* Function Prototype */ void rec_fibonacci(int); void main(int argc, char *argv[])/* Command line Arguments*/ { int number = atoi(argv[1]); printf("%dt%d", first, second); /* To print first and second number of fibonacci series */ rec_fibonacci(number); printf("n"); } /* Code to print fibonacci series using recursive function */ void rec_fibonacci(int num) { if (num == 2) /* To exit the function as the first two numbers are already printed */ { return; } third = first + second; printf("t%d", third); first = second; second = third; num--; rec_fibonacci(num); } Output: $ cc arg6.c $ a.out 10 0 1 1 2 3 5 8 13 21 34 PART-C 1.(i) Write the case study of “How sequential accessfile isdifferfrom Random access file”.(10) Sequential accessfile : – Cannotbe modifiedwithoutthe riskof destroyingotherdata
  • 33. – Fieldscanvary insize • Differentrepresentationinfilesandscreenthaninternal representation • Use fscanf to read fromthe file andfprintf towrite afile. • Data read frombeginningtoend • File positionpointer-Indicatesnumberof nextbyte tobe read/ written • You mightfindituseful toexamine yourworkloadtodeterminewhetheritaccessesdatarandomlyor sequentially.If youfinddiskaccessispredominantlyrandom, youmightwanttopayparticularattention to the activitiesbeingdone andmonitorforthe emergence of abottle neck.. Data in random access files: – Unformatted (stored as "raw bytes" ) • All data of the same type (ints, for example) uses the same amount of memory • All records of the same type have a fixed length • Data not human readable • fread and fwrite functions used – Access individual records without searching through other records – Instant access to records in a file – Data can be inserted without destroying other data – Data previously stored can be updated or deleted without overwriting • Implemented using fixed length records – Sequential files do not have fixed length records
  • 34. 1 /* Fig. 11.3: fig11_03.c 2 Create a sequential file */ 3 #include <stdio.h> 4 5 int main() 6 { 7 int account; 8 char name[ 30 ]; 9 double balance; 10 FILE *cfPtr; /* cfPtr = clients.dat file pointer */ 11 12 if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL ) 13 printf( "File could not be openedn" ); 14 else { 15 printf( "Enter the account, name, and balance.n" ); 16 printf( "Enter EOF to end input.n" ); 17 printf( "? " ); 18 scanf( "%d%s%lf", &account, name, &balance ); 19 20 while ( !feof( stdin ) ) { 21 fprintf( cfPtr, "%d %s %.2fn", 22 account, name, balance ); 23 printf( "? " ); 24 scanf( "%d%s%lf", &account, name, &balance ); 25 } 26 27 fclose( cfPtr ); 28 } 29 30 return 0; 31 }
  • 35. 1 /* Fig. 11.11: fig11_11.c 2 Creating a randomly accessed file sequentially */ 3 #include <stdio.h> 4 5 struct clientData { 6 int acctNum; 7 char lastName[ 15 ]; 8 char firstName[ 10 ]; 9 double balance; 10 }; 11 12 int main() 13 { 14 int i; 15 struct clientData blankClient = { 0, "", "", 0.0 }; 16 FILE *cfPtr; 17 18 if ( ( cfPtr = fopen( "credit.dat", "w" ) ) == NULL ) 19 printf( "File could not be opened.n" ); 20 else { 21 22 for ( i = 1; i <= 100; i++ ) 23 fwrite( &blankClient, 24 sizeof( struct clientData ), 1, cfPtr ); 25 26 fclose( cfPtr ); 27 } 28 29 return 0; 30 }
  • 36. (ii) Write a C program to write all the membersof an array ofstructures to a file usingfwrite().Read the array from the file anddisplay on the screen.(5) #include <stdio.h> struct s { char name[50]; int height; }; int main(){ struct s a[5],b[5]; FILE *fptr; int i; 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: %snHeight: %d",b[i].name,b[i].height); } fclose(fptr); } 2. Summarize the various file openingmodeswiththeirdescriptions.(15) File Modes r Open a text file for reading. w Create a text file for writing. If the file exists, it is overwritten. a Open a text file in append mode. Text is added to the end of the file. rb Open a binary file for reading. wb Create a binary file for writing. If the file exists, it is overwritten. ab Open a binary file in append mode. Data is added to the end of
  • 37. the file. r+ Open a text file for reading and writing. w+ Create a text file for reading and writing. If the file exists, it is overwritten. a+ Open a text file for reading and writing at the end. r+b or rb+ Open binary file for reading and writing. w+b or wb+ Create a binary file for reading and writing. If the file exists, it is overwritten. a+b or ab+ Open a text file for reading and writing at the end. 3. Developa C Program to merge two files.(15) #include<stdio.h> #include<stdlib.h> int main() { FILE *fs1, *fs2, *ft; char ch, file1[20], file2[20], file3[20]; printf("Enter name of first filen"); gets(file1); printf("Enter name of second filen"); gets(file2); printf("Enter name of file which will store contents of two filesn"); gets(file3); fs1 = fopen(file1,"r"); fs2 = fopen(file2,"r"); if( fs1 == NULL || fs2 == NULL ) { perror("Error "); printf("Press any key to exit...n"); getch(); exit(EXIT_FAILURE); } ft = fopen(file3,"w"); if( ft == NULL ) { perror("Error ");
  • 38. printf("Press any key to exit...n"); exit(EXIT_FAILURE); } while( ( ch = fgetc(fs1) ) != EOF ) fputc(ch,ft); while( ( ch = fgetc(fs2) ) != EOF ) fputc(ch,ft); printf("Two files were merged into %s file successfully.n",file3); fclose(fs1); fclose(fs2); fclose(ft); return 0; } 4. Examine with example forthe functionsrequiredin binary file I/O operations.(15) Binary File I/O uses fread and fwrite. The declarations for each are similar: size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); Both of these functions deal with blocks of memories - usually arrays. Because they accept pointers, you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory. Example Program: #include <stdio.h> struct s { char name[50]; int height; }; int main(){ struct s a[5],b[5]; FILE *fptr; int i; fptr=fopen("file.txt","wb"); for(i=0;i<5;++i) {
  • 39. 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: %snHeight: %d",b[i].name,b[i].height); } fclose(fptr); }