Professional Documents
Culture Documents
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.
When dealing with files, there are two types of files they are:
Function Description
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.
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);
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
(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+");
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.
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
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
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
return(0);
}
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.
rename("hello.txt", "byebye.txt");
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.
remove("hello.txt");
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
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:
Example:
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:
b) The fscanf() function is used to read mixed type form the file.
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.
#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
Example
#include <stdio.h>
int main () {
char str1[20], str2[30];
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
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:
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.
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program takes a number from user and stores in the file program.txt.
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fscanf(fptr,"%d", &num);
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.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
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);
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
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.
fread(address_data,size_data,numbers_data,pointer_to_file);
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *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.
An C programming language offers many inbuilt functions for handling files. They are given
below.
fputchar () function writes a character onto the output screen from keyboard
fputchar ()
input.
SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.
rewind () rewind () function moves file pointer position to the beginning of the file.
#include <dirent.h>
int main(void)
return 0;
}
printf("%s\n", de->d_name);
closedir(dr);
return 0;
Output:
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;
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.
C programming is awesome.
I love C programming.
How are you doing?
162 }
163}
164
166{
168
178}
10. Write a C program Finding average of numbers stored in sequential access file.(13)
#include <stdio.h>
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);
return 0;
}
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.
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.
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.
int main()
{
FILE *fileptr;
int count_lines = 0;
char filechar[40], chr;
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)
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. .
#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
a Open a text file in append mode. Text is added to the end of the
file.
w+ Create a text file for reading and writing. If the file exists, it is
overwritten.
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+
#include<stdio.h>
#include<stdlib.h>
int main()
{
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
exit(EXIT_FAILURE);
}
ft = fopen(file3,"w");
if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
}
4. Examine with example for the functions required in binary file I/O operations.(15)
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);
}