You are on page 1of 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. Mention different type of file accessing.


 Sequential access and Random access

When dealing with files, there are two types of files they are:

1. Text files and 2. Binary files.

3. Distinguish between Sequential access and Random access.


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 is meant by command line argument.? Give an example.


 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 out the various file handling function.


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() and ftell() 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 in C ?


File can be created as 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 files are needed?


 Files are needed for the computer that stores data, information, settings, or commands used
with a computer program.
 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 read and 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 terms Field, Record and File.


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() and getchar()

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 and fscanf()

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. Distinguish between following:‐

(i).printf () and fprintf()

ii).feof() and ferror()

(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.%s\n", 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. Which of the following operations can be performed on the file "NOTES.TXT" using the below code?
FILE *fp;
fp = fopen("NOTES.TXT", "r+");

Ans.Open an existing file for update (reading and writing).

14. Identify the different types of file.

A file can be of two types 


• Text file
• Binary file

Text files:A text file can be a stream of characters that a computer can process sequentially. A text
stream in C is a special kind of file. It is not only processed sequentially but only in forward direction.

A binary file is different to a text file. It is a collection of bytes. In C Programming Language a byte and a
character are equivalent. No special processing of the data occurs and each byte of data is transferred to
or from the disk unprocessed.
15. Identify the difference between Append and Write Mode.

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write
in a file. In both the modes, new file is created if it does not already exist. The only difference they have
is, when you open a file in the write mode, the file is reset, resulting in deletion of any data already
present in the file. While in append mode this will not happen. Append mode is used to append or add
data to the existing data of file, if any. Hence, when you open a file in Append (a) mode, the cursor is
positioned at the end of the present data in the file.

16. What is the 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 find the 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 : %d\n", size);
15. fclose(fp);
16. }
18. Write the Steps for Processing a File

19. Write a code in C to defining and opening a File.

#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 does argv and argc indicate in command-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 following file manipulation functions with examples.(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 prototyped below:

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

ii) remove()’ function can be used to explicitly close/delete a file specified by argument. If the specified
file is open while remove() was called, behaviour is implementation defined.

For example, for an existing file “hello.txt”,

remove("hello.txt");

They are prototyped below:

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("%s\n", str);
        // fflush(stdin);
    }
    return 0;
}

Input:

geeks
geeksforgeeks

Output:

geeks
geeksforgeeks

2. Distinguish between the following functions.(13)

a) getc() and getchar().(3)

b) scanf() and fscanf().(3)

c) printf() and fprintf().(3)

d) feof() and ferror().(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.

Syntax of 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.

Example of fscanf() 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%d\t%s\t%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: %s\n", 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.%s\n", 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 and explain a C 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 : Open Target File in Write 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. Explain the read and write operations on a file with an 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.

Writing to 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.

Reading from a text file

Example 2: Read from 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.

Writing to a binary file

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.

Reading from a binary file

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: %d\tn2: %d\tn3: %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 used in a file with example.(13)

An C programming language offers many inbuilt functions for handling files. They are given
below.

File handling functions Description

fopen () fopen () function creates a new file or opens an existing file.

fclose () fclose () function closes an opened file.

getw () getw () function reads an integer from file.

putw () putw () functions writes an integer to file.

fgetc () fgetc () function reads a character from file.

fputc () fputc () functions write a character to file.


fgets () fgets () function reads string from a file, one line at a time.

fputs () fputs () function writes string to a file.

feof () feof () function finds end of file.

fgetchar () fgetchar () function reads a character from keyboard.

fprintf () fprintf () function writes formatted data to a file.

fscanf () fscanf () function reads formatted data from a file.

fputchar () function writes a character onto the output screen from keyboard
fputchar ()
input.

fseek () fseek () function moves file pointer position to given location.

SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.

SEEK_CUR SEEK_CUR moves file pointer position to given location.

SEEK_END SEEK_END moves file pointer position to the end of file.

ftell () ftell () function gives current position of file pointer.

rewind () rewind () function moves file pointer position to the beginning of the file.

remove () remove () function deletes a file.

fflush () fflush () function flushes a file.

6. Write a C Program to print names of all Files present in a Directory.(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("%s\n", de->d_name);

    closedir(dr);   

    return 0;

Output:

All files and subdirectories


of current directory

DESCRIPTION

The type DIR, which is defined in the header <dirent.h>, represents a directory stream, which is an
ordered sequence of all the directory entries in a particular directory. Directory entries represent files;
files may be removed from a directory or added to a directory asynchronously to the operation of
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 a C Program to read content of a File and display 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 a C Program to print the contents of a File in reverse.(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 a C Program Transaction processing using random access files.(13)


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
9. Write a C Program Transaction processing using random
already in the file. */
access files.(16)
6#include <stdio.h>
7
8struct clientData {
9 int acctNum;
10 char lastName[ 15 ];
11 char firstName[ 10 ];
12 double balance;
13};
14
15int enterChoice( void );
16void textFile( FILE * );
17void updateRecord( FILE * );
18void newRecord( FILE * );
19void deleteRecord( FILE * );
20
21int 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
54void 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%10s\n",
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.2f\n",
72 client.acctNum, client.lastName,
73 client.firstName, client.balance );
74 }
75
76 fclose( writePtr );
77 }
78
79}
80
81void 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.2f\n\n",
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.2f\n",
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, balance\n? " );
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 choice\n"

170 "1 - store a formatted text file of acounts called\n"

171 " \"accounts.txt\" for printing\n"

172 "2 - update an account\n"

173 "3 - add a new account\n"

174 "4 - delete an account\n"

175 "5 - end program\n? " );

176 scanf( "%d", &menuChoice );

177 return menuChoice;

178}
10. Write a C program Finding average of numbers stored in sequential access 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/arguments supplied to the program when it is invoked. They are used to


control program from outside instead of hard coding those values inside the code.
 In real time application, it will happen to pass arguments to the main program itself.
These arguments are passed to the main () function while executing binary file from
command line.
Syntax:

int main(int argc, char *argv[])

Here argc counts the number of arguments on the command line and argv[ ] is a pointer array
which holds pointers of type char which points to the arguments passed to the program.

Example for Command Line Argument


#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[])


{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}

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

12. Develop a C Program to find the number of lines in a 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 file\n", count_lines, filechar);
return 0;
}
13. Write a C Program to calculate the factorial of 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("%d\t%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 access file is differ from Random access file”.(10)

Sequential access file :

– Cannot be modified without the risk of destroying other data


– Fields can vary in size
• Different representation in files and screen than internal representation
• Use fscanf to read from the file and fprintf to write a file.
• Data read from beginning to end
• File position pointer-Indicates number of next byte to be read / written

You might find it useful to examine your workload to determine whether it accesses data randomly or
sequentially. If you find disk access is predominantly random, you might want to pay particular attention
to the activities being done and monitor for the emergence of a bottle 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
5int 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 opened\n" );
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 %.2f\n",
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
5struct clientData {
6 int acctNum;
7 char lastName[ 15 ];
8 char firstName[ 10 ];
9 double balance;
10};
11
12int 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 members of an array of structures to a file using fwrite().Read
the array from the file and display 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: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}

2. Summarize the various file opening modes with their descriptions. (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 Open binary file for reading and writing.


rb+

w+b or Create a binary file for reading and writing. If the file exists, it is
wb+ overwritten.

a+b or Open a text file for reading and writing at the end.
ab+

3. Develop a 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 file\n");


gets(file1);

printf("Enter name of second file\n");


gets(file2);

printf("Enter name of file which will store contents of two files\n");


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 for the functions required in 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: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}

You might also like