SlideShare a Scribd company logo
1 of 65
Advance-C
FYBBA(CA)
By, Vrushali Solanke.
Syllabus:Chapter-2
File handling:
2.1 File
2.1.1 Def
2.1.2 File Opening Modes
2.1.3 Types of files - text and binary,
2.2 Functions: fopen(), fclose(), fgetc(), fputc(), fgets(), fputs(), fscanf(),
fprintf(), getw(), putw(), fread(), fwrite(), fseek(),ftell() etc
2.3 File Management
2.3.1 Opening/Closing a File
2.3.2. Input/Output operations on Files
2.3.3. Error Handling During I/O Operations
2.3.4. Command Line Arguments
2.4. Random Access File
File
• A collection of data or information that are stored on a computer known as file.
• A file is a collection of bytes stored on a secondary storage device.
There are four different types of file
• Data files
• Text files
• Program files
• Directory files
• Different types of file store different types of information
• A file has a beginning and an end.
• We need a marker to mark the current position of the file from the beginning (in terms
of bytes) while reading and write operation, takes place on a file.
• Initially the marker is at the beginning of the file. We can move the marker to any other
position in the file.
• The new current position can be specified as an offset from the beginning the file.
File Streams:
• A stream refers to the flow of data (in bytes) from one place to another
(from program to file or vice-versa).
There are two types of streams
1)Text Stream
• It consists of sequence of characters
• Each line of characters in the stream may be terminated by a newline
character.
• Text streams are used for textual data, which has a consistent appearance
from one environment to another or from one machine to another
2)Binary Stream
• It is a series of bytes.
• Binary streams are primarily used for non-textual data, which is required
to keep exact contents of the file.
• ASCII text file
1.A text file can be a stream of characters that a computer can process
sequentially.
2.It is processed only in forward direction.
3.It is opened for one kind of operation (reading, writing, or appending)
at any give time.
• Binary files:
1.A binary file is a file consisting of collection of bytes.
2.A binary file is also referred to as a character stream
Function on File
Naming a File:
• A file is identified by its name.
• This name is divided into two parts
1)File Name
• It consists of alphabets and digits.
• Special characters are also supported, but it depends on the operating
system we use.
2) Extension
• It describes the file type
Steps in Processing a File
1. Create the stream via a pointer variable using the FILE structure:
FILE *p;
2. Open the file, associating the stream name with the file name.
3. Read or write the data.
4. Close the file.
• File Open Modes
• More on File Open Modes
• r+ - open for reading and writing, start at beginning
• w+ - open for reading and writing (overwrite file)
• a+ - open for reading and writing (append if file exists)
File Open
• The file open function (fopen) serves two purposes: – It makes the connection between the physical
file and the stream. – It creates “a program file structure to store the information” C needs to process the
file.
Syntax: filepointer=fopen(“filename”, “mode”);
The file mode tells C how the program will use the file.
• The filename indicates the system name and location for the file.
• We assign the return value of fopen to our pointer variable:
filepointer = fopen(“MYFILE.TXT”, “w”);
filepointer = fopen(“A:MYFILE.TXT”, “w”);
Closing a File
• When we finish with a mode, we need to close the file before ending
the program or beginning another mode with that same file.
• To close a file, we use fclose and the pointer variable:
fclose(filepointer);
• Mode = “r” − open for reading, this
mode will open the file for reading
purpose only, i.e. the contents can only
be viewed, nothing else like edits can be
done to it.
• This mode cannot create a new file
and fopen() returns NULL, if we try to
create a new file using this mode.
Example
#include <stdio.h>
int main(){
FILE * file;
if (file == fopen("hello.txt", "r")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new
file using r mode");
fclose(file);
return 0;
}
Output
File opened successfully in read mode
We have created a file named hello.txt in our
current directory but if we try to access other file
then we will get “The file is not present! cannot
create a new file using r mode” as output.
• Mode = “w” − open for writing only, this
mode will open the file if present in the
current directory for writing only i.e.
reading operation cannot be performed. If
the file is not present in the current
directory, the program will create a new file
and open it for writing.
• If we open a file that contains some text in
it, the contents will be overwritten.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("helo.txt", "w")){
printf("File opened successfully
in write mode or a new file is
created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in write
mode or a new file is created
You can see here, we have tried to open file
“helo.txt” which is not present in the directory,
still the function returned the success message
because it has create a file named “helo.txt”.
• Mode = “a” − open for append only,
this mode will open the file if present
in the current directory for writing
only i.e. reading operation cannot be
performed. If the file is not present
in the current directory, the program
will create a new file and open it for
writing.
• If we open a file that contains some
text in it, the contents will not be
overwritten; instead the new text will
be added after the existing text in
the file.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "a")){
printf("File opened successfully in
append mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in append mode or a
new file is created
• Mode = “r+” − open for reading and writing
both, this mode will open the file for both
reading and writing purposes i.e. both read
and write operations can be performed to the
file.
• This mode cannot create a new file
and open() returns NULL, if we try to create
a new file using this mode.If we open a file
that contains some text in it and write
something, the contents will be overwritten.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "r+")){
printf("File opened successfully in
read and write both");
}
else
printf("The file is not present! cannot
create a new file using r+ mode");
fclose(file);
return 0;
}
Output
File opened successfully in read and
write both
We have created a file named hello.txt in our
current directory but if we try to access another
file then we will get “The file is not present!
cannot create a new file using r+ mode” as
output.
• Mode = “w+” − open for writing and reading,
this mode will open the file if present in the
current directory for writing and reading
operation both. If the file is not present in the
current directory, the program will create a new
file and open it for reading and writing.
• If we open a file that contains some text in it,
the contents will be overwritten.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("helo.txt", "w+")){
printf("File opened successfully in
read-write mode or a new file is
created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in read-write
mode or a new file is created
You can see here, we have tried to open file “helo.txt”
which is not present in the directory, still the function
returned the success message because it has create
a file named “helo.txt”.
• Mode = “a+” − open for read and append, this
mode will open the file if present in the current
directory for both reading and writing. If the file is
not present in the current directory, the program
will create a new file and open it for reading and
writing.
• If we open a file that contains some text in it, the
contents will not be overwritten; instead the new
text will be added after the existing text in the file.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "a+")){
printf("File opened successfully in
read-append mode or a new file is
created");
}
else
printf("Error!");
fclose(file);
return 0;
}
Output
File opened successfully in read-append mode
or a new file is created
• Reading Data for from an existing file
• We can read content of a file in c using the
fscanf() and fgets() and fgetc() functions.
All are used to read contents of a file. Let’s
see the working of each of the function −
• fscanf()
• The fscanf() function is used to read
character set i.e strings from the file. It
returns the EOF, when all the content of
the file are read by it.
• Syntax
• int fscanf(FILE *stream, const
char *charPointer[])
• Parameters
• FILE *stream: the pointer to
the opened file.
• const char *charPointer[]:
string of character.
#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
while(fscanf(file,"%s", str)!=EOF){
printf("%s", str); }
}else
printf("Error!”);
fclose(file);
return 0;
}
• fgets()
• The fgets() function in C is used to
read string from the stream.
• Syntax
• char* fgets(char *string, int
length, FILE *stream)
• Parameter
• char *string: It is a string
which will store the data
from the string.
• int length: It is an int
which gives the length of
string to be considered.
• FILE *stream: It is the
pointer to the opened file.
#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
printf("%s", fgets(str, 50, file));
}
fclose(file);
return 0;
}
Output
C programming
• fgetc()
• The fgetc() function in C is used to return a single
character from the file. It gets a character from the
file and returns EOF at the end of file.
• Syntax
• int fgetc(FILE *stream)
• Parameter
• FILE *stream: It is the pointer to
the opened file.
#include <stdio.h>
int main(){
FILE * file;
char str;
if (file = fopen("hello.txt", "r")){
while((str=fgetc(file))!=EOF)
printf("%c",str);
}
fclose(file);
return 0;
}
Output
Learn programming at tutorials Point
• Writing Data to a file in C
• We can write data to a file in C using the
fprintf(), fputs(), fputc() functions. All are
used to write contents to a file.
• fprintf()
• The fprintf() function is used to write data
to a file. It writes a set of characters in a
file.
• Syntax
• int fprintf(FILE *stream, char
*string[])
• Parameters
• FILE for *stream: It is the
pointer to the opened file.
• char *string[]: It is the
character array that we want to
write in the file.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fprintf(file, “File Handling”) >= 0)
printf("Write operation successful");
}
fclose(file);
return 0;
}
Output
Write operation successful
• fputs()
• The fputs() function in C can be used to write to a
file. It is used to write a line (character line) to the
file.
• Syntax
• int fputs(const char *string, FILE
*stream)
• Parameters
• Constant char *string[]: It is the
character array that we want to write
in the file.
• FILE for *stream: It is the pointer
to the opened file.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt",
"w")){
if(fputs("tutorials Point",
file) >= 0)
printf("String written to the
file successfully...");
}
fclose(file);
return 0;
}
Output
String written to the file
successfully…
• fputc()
• The fputc() function is used to write a
single character to the file.
• Syntax
• int fputc(char character ,
FILE *stream)
• Parameters
• char character : It is the
character that we want to
write in the file.
• FILE for *stream: It is the
pointer to the opened file.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
fputc('T', file);
}
fclose(file);
return 0;
}
Output
‘T’ is written to the file.
• fclose()
• The fclose() function is used to
close the open file. We should
close the file after performing
operations on it to save the
operations that we have applied to
it.
• Syntax
• fclose(FILE *stream)
• Parameters
• FILE for *stream: It is
the pointer to the opened
file.
#include <stdio.h>
int main(){
FILE * file;
char string[300];
if (file = fopen("hello.txt", "a+")){
while(fscanf(file,"%s", string)!=EOF){
printf("%s", string);
}
fputs("Hello", file);
}
fclose(file);
return 0;
}
Output
LearnprogrammingatTutorialsP
oint
• Sample Code 1
The following program reads the contents of file named a.txt and displays its
contents on the screen with the case of each character reversed.
/* Program revrese case of characters in a
file */
#include<stdio.h>
#include <ctype.h>
void main()
{
FILE * fp;
fp = fopen(“a.txt”, “r”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
while( !feof(fp))
{
ch = fgetc(fp);
if(isupper(ch))
putchar(tolower(ch));
else
if(islower(ch))
putchar(toupper(ch));
Else
putchar(ch);
}
fclose(fp);
}
• Sample Code 2
The following program displays the size of a file. The filename is passed as
command line argument.
/* Program to display size of a file */
#include<stdio.h>
void main(int argc, char *argv[])
{
FILE * fp;
long int size;
fp = fopen(argv[1], “r”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
fseek(fp, 0, SEEK_END);
/* move pointer to end of file */
size = ftell(fp);
printf(“The file size = %ld bytes”, size);
fclose(fp);
}
• Sample Code 3
The following program writes data (name, roll number) to a file named
student.txt , reads the written data and displays it on screen.
Include<stdio.h>
void main()
{
FILE * fp;
char str[20];
int num;
fp = fopen(“student.txt”, “w+”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
fprintf(fp,“%st%dn”, “ABC”, 1000);
fprintf(fp,“%st%dn”, “DEF”, 2000);
fprintf(fp,“%st%dn”, “XYZ”, 3000);
rewind(fp);
while( !feof(fp))
{
fscanf(fp,“%s%d”, str, &num);
printf(“%st%dn”, str, num);
}
fclose(fp);
}
• Error Handling in C
C language does not provide any direct support for error handling.
However a few methods and variables defined in error.h header file can be used to point out
error using the return statement in a function.
In C language, a function returns -1 or NULL value in case of any error and a
global variable errno is set with the error code.
What is errno?
Whenever a function call is made in C language, a variable named errno is associated with it.
It is a global variable, which can be used to identify which type of error was encountered while
function execution, based on its value.
Below we have the list of Error numbers and what does they mean.
C language uses the following
functions to represent error messages
associated with errno
•strerror() is defined
in string.h library. This
method returns a
pointer to the string
representation of the
current errno value.
•perror(): returns the
string passed to it along
with the textual
represention of the
current errno value.
OutPut:
Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
FILE *fp;
/* If a file, which does not
exists, is opened, we will get an
error */
fp = fopen("IWillReturnError.txt",
"r");
printf("Value of errno: %dn ",
errno);
printf("The error message is :
%sn", strerror(errno));
perror("Message from perror");
return 0;}
• C Program to copy content of one File into another File
#include<stdio.h>
#include<string.h>
void main()
{
/* File_1.txt is the file
with content and,
File_2.txt is the file in
which content of File_1 will
be copied. */
FILE *fp1, *fp2; char ch; int
pos;
if ((fp1 =
fopen("File_1.txt", "r")) ==
NULL)
{
printf("nFile cannot be
opened.");
return;
}
else {
printf("nFile opened for copy...n ");
}
fp2 = fopen("File_2.txt", "w");
fseek(fp1, 0L, SEEK_END);
// File pointer at end of file
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET);
// File pointer set at start
while (pos--)
{
ch = fgetc(fp1);
// Copying file character by character
fputc(ch, fp2);
}
fcloseall();
}
C Program to Read content of a File and Display it
• Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name
and salary of the employee.
1.#include <stdio.h>
2.void main()
3.{
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* o
pen for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists n");
12. return;
13. }
1. printf("Enter the idn");
2. scanf("%d", &id);
3. fprintf(fptr, "Id= %dn", id);
4. printf("Enter the name n");
5. scanf("%s", name);
6. fprintf(fptr, "Name= %sn", name);
7. printf("Enter the salaryn");
8. scanf("%f", &salary);
9. fprintf(fptr, "Salary= %.2fn", salary
);
10. fclose(fptr);
11.}
ERROR HANDLING DURING FILE I/O OPERATIONS
While dealing with files, it is possible that an error may occur. This error may occur due to following
reasons:
1.Reading beyond the end of file mark.
2. Performing operations on the file that has not still been opened.
3.Writing to a file that is opened in the read mode.
4.Opening a file with invalid filename.
5.Device overflow.
Such as, C programming does not provide direct support for error handling but being a system
programming language, it provides us access at lower level in the form of return values.
Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code
errno.
• It is set as a global variable and indicates an error occurred during any function call
• We can find various error codes defined in <error.h> header file
• So, a C programmer can check the returned values and can take appropriate action depending on the
return value. It is a good practice, to set errno to o at the time of initializing a program. A value of O
indicates that there is no error in the program.
What is errno?
• Whenever a function call is made in C language, a variable named errno is associated with it.
• It is a global variable, which can be used to identify which type of error was encountered while
function execution, based on its value.
• Below, table shows the list of Error numbers and what does they mean .
errno value Error
1 Operation not permitted
2 No such file or directory
3 No such process
4 Interrupted system call
5 I/O error
6 No such device or address
7 Argument list too long
8 Exec format error
9 Bad file number
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
1. feof():
The feof() function can be used to test for an end of file condition.
Syntax:
feof(FILE *file_pointer);
For example:
if(feof(fp))
printf("End of file");
2. ferror():
The ferror() function reports on the error state of the stream and returns true if an error has occurred.
The function clears the end of file and error indicator for the argument stream.
Library functions for error handling during file I/O operations:
Syntax:
ferror (FILE *file_pointer);
• For example:
• if(ferror(fp)!=0)
• printf("An error has occurred");
• 3. perror():
• The perror() function displays the string we
pass to it, followed by a colon, a space and
then the textual representation of the current
errno value.
• Syntax:
• void perror(const char *str);
• The function displays a string giving error
message as predefined in compiler for
particular error condition.
4. strerror():
The strerror() function, returns a pointer
to the textual representation of the
current errno value.
Syntax:
strerror(int errno);
5.stderr: you should use stderr file
stream to output all the errors.
Program: Write a program for
error handling.
#include<stdio.h>
#include<errno.h>
#include<string.h>
extern int errno;
int main()
{
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "r");
if (pf == NULL)
{
errnum = errno;
fprintf(stderr, "Value of errno: %dn", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %sn", strerror(
errnum));
}
else
{
fclose (pf);
}
return 0;
}
Output:
Value of errno: 2
Error printed by perror: No such file or directory.
Error opening file: No such file or directory.
5. Divide by Zero Error .
There are some situations where nothing can be done to handle the error. In c language one such
situation is division by zero.
We can do is avoid doing this because if we do so, C language is not able to understand what happened,
and gives a runtime error.
Best way to avoid this is to check the value of the divisor before using it in the division operations. We can
use if condition, and if it is found to be zero, just display a message and return from the function.
It is a common problem that at the time of dividing any number, programmers do not check if a divisor is
zero and finally it creates a runtime error
The code below fixes this by checking if the divisor is zero before dividing.
• Program: Write a program for divided by zero
error.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int dividend = 2e;
int divisor = 0;
int quotient;
if(divisor == 0)
{
fprintf(stderr, Division by zerol Exiting…n");
exit(-1);
}
quotient = dividend/divisory;
fprintf(stderr, "Value of Quotient
:%dn”,quotient);
exit(0);
}
Output:
Division by zero! Exiting…
6. Program Exit Status:
We can also use Exit Status constants in the exit() function to inform the calling function about the error.
The two constant values available for use, are EXIT_SUCCESS and EXIT FAILURE .
These are nothing but macros defined <stdlib.h> header file.
It is a common practice to exit with a value of EXIT_SUCCESS in case of program coming out after a
successful operation. Here. EXIT_SUCCESS is a macro and it is defined as 0.
If we have an error condition in our program and we are coming out then we should exit with a status
EXIT_FAILURE which is defined as -1. So let's write above program as follows.
• Program : Write a program for Exit status.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int dividend = 20;
int divisor = 5;
int quotient;
if( divisor == 0)
{
fprintf(stderr, "Division by zero! Exiting... n");
exit(EXIT_FAILURE);
}
quotient = dividend / divisor;
fprintf(stderr, "Value of quotient : %dn", quotient);
exit(EXIT_SUCCESS);
}
Output:
Value of quotient : 4
Program : Write a program to indicate exit status.
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
extern int errno;
void main()
{
char *ptr=malloc(100000000UL);
if(ptr==NULL)
{
puts("malloc failed");
puts(strerror(errno));
exit(EXIT_FAILURE);
}
else
{
free(ptr);
exit(EXIT_SUCCESS);
}
}
Explanation of program:
Here exit function is used to indicate exit status. It is
always a good practice to exit a program with a exit status.
EXIT_SUCCESS and EXIT_FAILURE are two macros
used to show exit status.
In case of program coming out after a successful
operation EXIT_SUCCESS is used to show successful
exit. It is defined as O.
EXIT_Failure is used in case of any failure in the program.
It is defined as -1.
• Program : Write a program for errors
handling during file I/O operations.
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();
fp=fopen("book.txt", “r");
if(fp==NULL){
printf("The file book.txt does
not exist");
getch();
}
fp=fopen("student.txt", "w");
if(fp==NULL)
{
printf("The read-only file students.txt cannot be opened in
write mode");
getch();
}
fp=fopen("text.txt","r");
fputc("a", fp);
if(ferror(fp))
{
printf("The file text.txt has been opened in read mode");
printf("but you are writing to it. n");
}
getch();
}
Output:
The file book.txt does not exist
The read-only file student.txt cannot opened in write mode
The file text.txt has been opened in read mode but you are writing to it.
RANDOM ACCESS FILE
• Random Access files consist of records that can be accessed in any sequence.
• This means the data is stored exactly as it appears in memory, thus saving processing time
(because no translation is necessary) both in when the file is written and in when it is read.
C standard library provides the following build-in functions to support this:
1. fseek()
• The position fseek() repositions the file pointer.
• The prototype of fseek() function is defined in stdio.h.
• It is used to set the file position pointer for the given stream. The variable offset is an integer
value that gives the number of bytes to move forward or backward in the file. The value of
offset may be positive or negative, provided it makes sense.
Syntax: fseek ( fp, offset, position);
Where, fp is a pointer to FILE representing a file.
offset is the number of bytes by which the file pointer is to be moved relative to
the byte number identified by the third parameter position.
• Position can take any one of the following three values 0,1 and 2.
Table:fseek() options
Position Symbolic_Constant Meaning
0 SEEK_SET Beginning of File
1 SEEK_CUR Current position of File
2 SEEK_END End of file
Function Meaning
feek(fp,0L,SEEK_SET); Moves to the beginning of the file
fseek(fp,0L, SEEK_CUR); Stay at the current position of the file
fseek(fp,0L, SEEK_END); Go to the End of File
fseek(fp,m,SEEK_CUR); Move forward by m bytes in the file form the current
location.
fseek(fp,-m, SEEK_CUR); Moves backwards by m bytes in the file from the
current location.
fseek_(fp,-m,SEEK_END); Moves backwards by m bytes in the file from the end of
the file
2. ftell()
• The function ftell() returns the current position of the file pointer.
• It is the position where the next input or output operation will be performed.
• Syntax:
position=ftell(fp);
Where, fp is a pointer to FILE type representing a file, the current position of the file pointer of
the file is returned be a function.
• When using ftell(), errors can occur due to the following reasons:
1. Using ftell(), with a device that cannot store data(e.g. Keyboard)
2. When position is larger than that can be represented in a long integer. This will usually happen when
dealing with very large files.
• It is useful when we have to deal with text file for which position of the data cannot be calculated.
Program 2.15: How to use ftell()
Function in C.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
int n;
fp=fopen("abc.txt", "w");
if (fp==NULL)
{
printf("n error in opening
file");
exit(1);
}
while((c=getchar()) !=EOF)
putc(c, fp);
n=ftell(fp);
fclose(fp);
fp=fopen("abc.txt","r");
if (fp==NULL)
{
printf("n error in opening file");
exit(1);
}
while(ftell(fp)<n)
{
c=fgetc(fp);
printf("%c",c);
}
fclose(fp);
getch();
}
3. rewind
• The rewind positions the file pointer to the beginning of a file.
• Syntax: rewind(fp);
Program : Write a program for rewind().
#include<stdio.h>
#include<conio.h>
void main()
{
FILE * fp;
char c;
clrscr();
fp=fopen("file.txt", “r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
rewind(fp);
while((c=fgetc(fp)) !=EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}
Output:
This is a simple text this is a simple text.
Program : Write a program to count the number of records in employee file.
#include<stdio.h>
#include<conio.h>
struct emp
{
int empno;
char name[20];
float salary;
}
void main()
{
FILE *fp;
int nor, last_byte;
clrscr();
fp=fopen("emp_dat","r");
last_byte=fseek(fp, 0, SEEK_END);
nor=last_byte/sizeof(struct emp);
printf("No. of records=%d", nor);
fclose(fp);
getch();
}
Output:
Number of records = 3
4. fgetpos(), fsetpos()
• It is to get the current position in a file, or set the current position in a file.
• It is just like ftell() and fseek() for most systems.
• The fsetpos() function moves the file position associated with stream to a new location within
the file according to the value of the object pointed to by pos.
• The fgetpos() function stores the current value of the file pointer associated with stream into
the object pointed to by pos.
• Both the fgetpos() and fsetpos() function save state information for wide-oriented files.
• The value stored in pos is unspecified, and it is usable only by fsetpos().
• Syntax:
fsetpos (File *stream, fpos_t *pos);
Where,The stream whose current position is to be determined.
Pos is the current position of stream to be stored.
• Program : Write a program for fgetpos() and fsetpos().
#include<stdio.h>
int main()
{
FILE * fp;
fpos_t position;
fp = fopen("file.txt","w+");
fgetpos(fp, &position);
fputs("Hello, students!", fp);
fsetpos(fp, &position);
fputs("Override previous contents...", fp);
fclose(fp);
return(0);
}
Output:
Override previous contents...
5. remove():
• It is used to erase a file.
• Syntax:
remove(char *filename);
Program : Write a program for remove file.
#include<stdio.h>
main()
{
remove("abc.txt");
return a;
}
COMMAND LINE ARGUMENTS
• In C, it is possible to accept command line arguments.
• Command line arguments are given after the name of a program in command line operating
systems like DOS or Linux, and are passed in to the program from operating system.
• To establish the data communication between a calling function and a called function.
• It is done through arguments; a calling function passes inputs to a called function which
perform required manipulations.
• Declarations of command line in main function:
• The main() can accept two arguments:
• 1. The first argument is an integer value that specifies number of command line
arguments.
• 2. The second argument is a full list of all of the command line arguments.
• Syntax:
• int main(int argc, char *argv[])
• Here, argc and argv[] are the formal arguments, which provide mechanism for collecting the
arguments given at command line when the program is launched for execution.
Program 2.12:To write a program using command
line arguments-Copying one file another file.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main(int arge, char *argv[ ])
{
FILE *fin, *fout;
char c;
Clrscr;
if(argc!=3)
{
printf("Invalid number of arguments");
exit(1);
}
fin=fopen(argv[1],"r");
fout=fopen(argv[2],"w");
while(!feof(fin))
{
C=fgetc(fin);
fputc(c, fout);
}
fclose(fin);
fclose(fout);
getch();
}
o/p=
c> copy text.txt text1.txt
As a result, the contents of text.dat are copied to
text1.txt
Summary
• Storage of information is read from or written on a auxiliary memory device is stored in the form of a
file.
• The data structure of a file is defined in stdio.h which creates a buffer area to store data in a file for
reading as well as writing.
• . fopen() is used to open a specified file.
• fclose()is used to close a specified file.
• fscanf() and fprintf() are used to perform input/output operation in files.
• fgetc() and fputc) are used to perform character input/output operation in files.
• fgets() and tputs() are used to perform string input/output operation in files,
• getw() and putw() are used to write an integer value into a file and read integer value from a file.
• fseek() is used to index a file and can be used to increment or decrement the filepointer.
• rewind() is used to reset the file pointer to the beginning of the file.
• file: The header file stdio.h defines a new data type called FILE.
• stdio.h: Each file used in a program must be associated with a pointer of its type. Three types of file
pointers are defined in stdio.h. They are stdin, stdout and stderr.
• printf() and scanf(): printf() and scanf() are used for performing input/output operations in
programs(without involving files).
• fgetchar() and fputchar(): Character input/output functions which act on files.
• feof(): The feof() function is used to check the end of file condition.
•
Trace the Output
(1) What will be the output of following
code?
#include<stdio.h>
int main()
{
FILE *fp=stdout;
int n;
fprintf(fp,"%dn ",45);
fprintf(stderr, "%d ",65);
return 0;
}
Output:
45 65.
(4) What will be the output of the program?
#include<stdio.h>
int main()
{
FILE *ptr;
char i;
ptr = fopen("myfile.c", "r");
while((i=fgetc (ptr)) !=NULL)
printf("%c", i);
return 0;
}
Output: infinite loop.
• (2) What will be the output of following
code?
• #include<stdio.h>
• int main()
• {
• char c;
• FILE * fp;
• fp=fopen("demo.txt","r");
• while((c=fgetc(fp))! =E0F)
• printf("%c",c);
• fclose(fp);
• return 0;
• }
• Output: It will print the content of file
demo.txt.
(3) What will be the output of the program?
#include<stdio.h>
int main()
{
FILE *fp1, *fp2;
fp1=fopen("file.c", "w");
fp2=fopen("file.c", "w");
fputc('A', fp1);
fputc('B',fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
Output: B.
What will be the output of the program?
#include<stdio.h>
int main()
{
FILE *fp;
char ch, str[7];
fp=fopen("try.c", "r");/* file 'try.c' contains "This is Nagpur"
fseek(fp, 9L, SEEK_CUR);
fgets(str, 5, fp);
puts(str);
return o;
}

More Related Content

What's hot (20)

File handling
File handlingFile handling
File handling
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
Files
FilesFiles
Files
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsing
 
File handling
File handlingFile handling
File handling
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Files in c++
Files in c++Files in c++
Files in c++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Python file handling
Python file handlingPython file handling
Python file handling
 
File handling in c
File handling in c File handling in c
File handling in c
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Python-files
Python-filesPython-files
Python-files
 
python file handling
python file handlingpython file handling
python file handling
 
Data file handling
Data file handlingData file handling
Data file handling
 

Similar to File Handling in C

file management in c language
file management in c languagefile management in c language
file management in c languagechintan makwana
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxarmaansohail9356
 
File management
File managementFile management
File managementsumathiv9
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptRaja Ram Dutta
 
File handing in C
File handing in CFile handing in C
File handing in Cshrishcg
 
lecture 10.pptx
lecture 10.pptxlecture 10.pptx
lecture 10.pptxITNet
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.pptHEMAHEMS5
 
Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Gheyath M. Othman
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15Vishal Dutt
 

Similar to File Handling in C (20)

pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
file management in c language
file management in c languagefile management in c language
file management in c language
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
File management
File managementFile management
File management
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
File handing in C
File handing in CFile handing in C
File handing in C
 
lecture 10.pptx
lecture 10.pptxlecture 10.pptx
lecture 10.pptx
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.ppt
 
Php files
Php filesPhp files
Php files
 
Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
637225560972186380.pdf
637225560972186380.pdf637225560972186380.pdf
637225560972186380.pdf
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
files.pptx
files.pptxfiles.pptx
files.pptx
 

Recently uploaded

MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 

Recently uploaded (20)

MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 

File Handling in C

  • 2. Syllabus:Chapter-2 File handling: 2.1 File 2.1.1 Def 2.1.2 File Opening Modes 2.1.3 Types of files - text and binary, 2.2 Functions: fopen(), fclose(), fgetc(), fputc(), fgets(), fputs(), fscanf(), fprintf(), getw(), putw(), fread(), fwrite(), fseek(),ftell() etc 2.3 File Management 2.3.1 Opening/Closing a File 2.3.2. Input/Output operations on Files 2.3.3. Error Handling During I/O Operations 2.3.4. Command Line Arguments 2.4. Random Access File
  • 3. File • A collection of data or information that are stored on a computer known as file. • A file is a collection of bytes stored on a secondary storage device. There are four different types of file • Data files • Text files • Program files • Directory files • Different types of file store different types of information • A file has a beginning and an end. • We need a marker to mark the current position of the file from the beginning (in terms of bytes) while reading and write operation, takes place on a file. • Initially the marker is at the beginning of the file. We can move the marker to any other position in the file. • The new current position can be specified as an offset from the beginning the file.
  • 4.
  • 5.
  • 6.
  • 7. File Streams: • A stream refers to the flow of data (in bytes) from one place to another (from program to file or vice-versa). There are two types of streams 1)Text Stream • It consists of sequence of characters • Each line of characters in the stream may be terminated by a newline character. • Text streams are used for textual data, which has a consistent appearance from one environment to another or from one machine to another 2)Binary Stream • It is a series of bytes. • Binary streams are primarily used for non-textual data, which is required to keep exact contents of the file.
  • 8. • ASCII text file 1.A text file can be a stream of characters that a computer can process sequentially. 2.It is processed only in forward direction. 3.It is opened for one kind of operation (reading, writing, or appending) at any give time. • Binary files: 1.A binary file is a file consisting of collection of bytes. 2.A binary file is also referred to as a character stream
  • 10.
  • 11. Naming a File: • A file is identified by its name. • This name is divided into two parts 1)File Name • It consists of alphabets and digits. • Special characters are also supported, but it depends on the operating system we use. 2) Extension • It describes the file type
  • 12. Steps in Processing a File 1. Create the stream via a pointer variable using the FILE structure: FILE *p; 2. Open the file, associating the stream name with the file name. 3. Read or write the data. 4. Close the file.
  • 13. • File Open Modes
  • 14. • More on File Open Modes
  • 15. • r+ - open for reading and writing, start at beginning • w+ - open for reading and writing (overwrite file) • a+ - open for reading and writing (append if file exists) File Open • The file open function (fopen) serves two purposes: – It makes the connection between the physical file and the stream. – It creates “a program file structure to store the information” C needs to process the file. Syntax: filepointer=fopen(“filename”, “mode”); The file mode tells C how the program will use the file. • The filename indicates the system name and location for the file. • We assign the return value of fopen to our pointer variable: filepointer = fopen(“MYFILE.TXT”, “w”); filepointer = fopen(“A:MYFILE.TXT”, “w”);
  • 16.
  • 17. Closing a File • When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. • To close a file, we use fclose and the pointer variable: fclose(filepointer);
  • 18. • Mode = “r” − open for reading, this mode will open the file for reading purpose only, i.e. the contents can only be viewed, nothing else like edits can be done to it. • This mode cannot create a new file and fopen() returns NULL, if we try to create a new file using this mode. Example #include <stdio.h> int main(){ FILE * file; if (file == fopen("hello.txt", "r")){ printf("File opened successfully in read mode"); } else printf("The file is not present! cannot create a new file using r mode"); fclose(file); return 0; } Output File opened successfully in read mode We have created a file named hello.txt in our current directory but if we try to access other file then we will get “The file is not present! cannot create a new file using r mode” as output.
  • 19. • Mode = “w” − open for writing only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing. • If we open a file that contains some text in it, the contents will be overwritten. #include <stdio.h> int main(){ FILE * file; if (file = fopen("helo.txt", "w")){ printf("File opened successfully in write mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; } Output File opened successfully in write mode or a new file is created You can see here, we have tried to open file “helo.txt” which is not present in the directory, still the function returned the success message because it has create a file named “helo.txt”.
  • 20. • Mode = “a” − open for append only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing. • If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file. #include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "a")){ printf("File opened successfully in append mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; } Output File opened successfully in append mode or a new file is created
  • 21. • Mode = “r+” − open for reading and writing both, this mode will open the file for both reading and writing purposes i.e. both read and write operations can be performed to the file. • This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.If we open a file that contains some text in it and write something, the contents will be overwritten. #include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "r+")){ printf("File opened successfully in read and write both"); } else printf("The file is not present! cannot create a new file using r+ mode"); fclose(file); return 0; } Output File opened successfully in read and write both We have created a file named hello.txt in our current directory but if we try to access another file then we will get “The file is not present! cannot create a new file using r+ mode” as output.
  • 22. • Mode = “w+” − open for writing and reading, this mode will open the file if present in the current directory for writing and reading operation both. If the file is not present in the current directory, the program will create a new file and open it for reading and writing. • If we open a file that contains some text in it, the contents will be overwritten. #include <stdio.h> int main(){ FILE * file; if (file = fopen("helo.txt", "w+")){ printf("File opened successfully in read-write mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; } Output File opened successfully in read-write mode or a new file is created You can see here, we have tried to open file “helo.txt” which is not present in the directory, still the function returned the success message because it has create a file named “helo.txt”.
  • 23. • Mode = “a+” − open for read and append, this mode will open the file if present in the current directory for both reading and writing. If the file is not present in the current directory, the program will create a new file and open it for reading and writing. • If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file. #include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "a+")){ printf("File opened successfully in read-append mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; } Output File opened successfully in read-append mode or a new file is created
  • 24. • Reading Data for from an existing file • We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used to read contents of a file. Let’s see the working of each of the function − • fscanf() • The fscanf() function is used to read character set i.e strings from the file. It returns the EOF, when all the content of the file are read by it. • Syntax • int fscanf(FILE *stream, const char *charPointer[]) • Parameters • FILE *stream: the pointer to the opened file. • const char *charPointer[]: string of character. #include <stdio.h> int main(){ FILE * file; char str[500]; if (file = fopen("hello.txt", "r")){ while(fscanf(file,"%s", str)!=EOF){ printf("%s", str); } }else printf("Error!”); fclose(file); return 0; }
  • 25. • fgets() • The fgets() function in C is used to read string from the stream. • Syntax • char* fgets(char *string, int length, FILE *stream) • Parameter • char *string: It is a string which will store the data from the string. • int length: It is an int which gives the length of string to be considered. • FILE *stream: It is the pointer to the opened file. #include <stdio.h> int main(){ FILE * file; char str[500]; if (file = fopen("hello.txt", "r")){ printf("%s", fgets(str, 50, file)); } fclose(file); return 0; } Output C programming
  • 26. • fgetc() • The fgetc() function in C is used to return a single character from the file. It gets a character from the file and returns EOF at the end of file. • Syntax • int fgetc(FILE *stream) • Parameter • FILE *stream: It is the pointer to the opened file. #include <stdio.h> int main(){ FILE * file; char str; if (file = fopen("hello.txt", "r")){ while((str=fgetc(file))!=EOF) printf("%c",str); } fclose(file); return 0; } Output Learn programming at tutorials Point
  • 27. • Writing Data to a file in C • We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write contents to a file. • fprintf() • The fprintf() function is used to write data to a file. It writes a set of characters in a file. • Syntax • int fprintf(FILE *stream, char *string[]) • Parameters • FILE for *stream: It is the pointer to the opened file. • char *string[]: It is the character array that we want to write in the file. #include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "w")){ if(fprintf(file, “File Handling”) >= 0) printf("Write operation successful"); } fclose(file); return 0; } Output Write operation successful
  • 28. • fputs() • The fputs() function in C can be used to write to a file. It is used to write a line (character line) to the file. • Syntax • int fputs(const char *string, FILE *stream) • Parameters • Constant char *string[]: It is the character array that we want to write in the file. • FILE for *stream: It is the pointer to the opened file. #include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "w")){ if(fputs("tutorials Point", file) >= 0) printf("String written to the file successfully..."); } fclose(file); return 0; } Output String written to the file successfully…
  • 29. • fputc() • The fputc() function is used to write a single character to the file. • Syntax • int fputc(char character , FILE *stream) • Parameters • char character : It is the character that we want to write in the file. • FILE for *stream: It is the pointer to the opened file. #include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "w")){ fputc('T', file); } fclose(file); return 0; } Output ‘T’ is written to the file.
  • 30. • fclose() • The fclose() function is used to close the open file. We should close the file after performing operations on it to save the operations that we have applied to it. • Syntax • fclose(FILE *stream) • Parameters • FILE for *stream: It is the pointer to the opened file. #include <stdio.h> int main(){ FILE * file; char string[300]; if (file = fopen("hello.txt", "a+")){ while(fscanf(file,"%s", string)!=EOF){ printf("%s", string); } fputs("Hello", file); } fclose(file); return 0; } Output LearnprogrammingatTutorialsP oint
  • 31. • Sample Code 1 The following program reads the contents of file named a.txt and displays its contents on the screen with the case of each character reversed. /* Program revrese case of characters in a file */ #include<stdio.h> #include <ctype.h> void main() { FILE * fp; fp = fopen(“a.txt”, “r”); if(fp==NULL) { printf(“File opening error”); exit(0); } while( !feof(fp)) { ch = fgetc(fp); if(isupper(ch)) putchar(tolower(ch)); else if(islower(ch)) putchar(toupper(ch)); Else putchar(ch); } fclose(fp); }
  • 32. • Sample Code 2 The following program displays the size of a file. The filename is passed as command line argument. /* Program to display size of a file */ #include<stdio.h> void main(int argc, char *argv[]) { FILE * fp; long int size; fp = fopen(argv[1], “r”); if(fp==NULL) { printf(“File opening error”); exit(0); } fseek(fp, 0, SEEK_END); /* move pointer to end of file */ size = ftell(fp); printf(“The file size = %ld bytes”, size); fclose(fp); }
  • 33. • Sample Code 3 The following program writes data (name, roll number) to a file named student.txt , reads the written data and displays it on screen. Include<stdio.h> void main() { FILE * fp; char str[20]; int num; fp = fopen(“student.txt”, “w+”); if(fp==NULL) { printf(“File opening error”); exit(0); } fprintf(fp,“%st%dn”, “ABC”, 1000); fprintf(fp,“%st%dn”, “DEF”, 2000); fprintf(fp,“%st%dn”, “XYZ”, 3000); rewind(fp); while( !feof(fp)) { fscanf(fp,“%s%d”, str, &num); printf(“%st%dn”, str, num); } fclose(fp); }
  • 34. • Error Handling in C C language does not provide any direct support for error handling. However a few methods and variables defined in error.h header file can be used to point out error using the return statement in a function. In C language, a function returns -1 or NULL value in case of any error and a global variable errno is set with the error code. What is errno? Whenever a function call is made in C language, a variable named errno is associated with it. It is a global variable, which can be used to identify which type of error was encountered while function execution, based on its value. Below we have the list of Error numbers and what does they mean.
  • 35. C language uses the following functions to represent error messages associated with errno •strerror() is defined in string.h library. This method returns a pointer to the string representation of the current errno value. •perror(): returns the string passed to it along with the textual represention of the current errno value. OutPut: Value of errno: 2 The error message is: No such file or directory Message from perror: No such file or directory #include <stdio.h> #include <errno.h> #include <string.h> int main () { FILE *fp; /* If a file, which does not exists, is opened, we will get an error */ fp = fopen("IWillReturnError.txt", "r"); printf("Value of errno: %dn ", errno); printf("The error message is : %sn", strerror(errno)); perror("Message from perror"); return 0;}
  • 36. • C Program to copy content of one File into another File #include<stdio.h> #include<string.h> void main() { /* File_1.txt is the file with content and, File_2.txt is the file in which content of File_1 will be copied. */ FILE *fp1, *fp2; char ch; int pos; if ((fp1 = fopen("File_1.txt", "r")) == NULL) { printf("nFile cannot be opened."); return; } else { printf("nFile opened for copy...n "); } fp2 = fopen("File_2.txt", "w"); fseek(fp1, 0L, SEEK_END); // File pointer at end of file pos = ftell(fp1); fseek(fp1, 0L, SEEK_SET); // File pointer set at start while (pos--) { ch = fgetc(fp1); // Copying file character by character fputc(ch, fp2); } fcloseall(); }
  • 37. C Program to Read content of a File and Display it
  • 38. • Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee. 1.#include <stdio.h> 2.void main() 3.{ 4. FILE *fptr; 5. int id; 6. char name[30]; 7. float salary; 8. fptr = fopen("emp.txt", "w+");/* o pen for writing */ 9. if (fptr == NULL) 10. { 11. printf("File does not exists n"); 12. return; 13. } 1. printf("Enter the idn"); 2. scanf("%d", &id); 3. fprintf(fptr, "Id= %dn", id); 4. printf("Enter the name n"); 5. scanf("%s", name); 6. fprintf(fptr, "Name= %sn", name); 7. printf("Enter the salaryn"); 8. scanf("%f", &salary); 9. fprintf(fptr, "Salary= %.2fn", salary ); 10. fclose(fptr); 11.}
  • 39. ERROR HANDLING DURING FILE I/O OPERATIONS While dealing with files, it is possible that an error may occur. This error may occur due to following reasons: 1.Reading beyond the end of file mark. 2. Performing operations on the file that has not still been opened. 3.Writing to a file that is opened in the read mode. 4.Opening a file with invalid filename. 5.Device overflow. Such as, C programming does not provide direct support for error handling but being a system programming language, it provides us access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.
  • 40. • It is set as a global variable and indicates an error occurred during any function call • We can find various error codes defined in <error.h> header file • So, a C programmer can check the returned values and can take appropriate action depending on the return value. It is a good practice, to set errno to o at the time of initializing a program. A value of O indicates that there is no error in the program. What is errno? • Whenever a function call is made in C language, a variable named errno is associated with it. • It is a global variable, which can be used to identify which type of error was encountered while function execution, based on its value. • Below, table shows the list of Error numbers and what does they mean .
  • 41. errno value Error 1 Operation not permitted 2 No such file or directory 3 No such process 4 Interrupted system call 5 I/O error 6 No such device or address 7 Argument list too long 8 Exec format error 9 Bad file number 10 No child processes 11 Try again 12 Out of memory 13 Permission denied
  • 42. 1. feof(): The feof() function can be used to test for an end of file condition. Syntax: feof(FILE *file_pointer); For example: if(feof(fp)) printf("End of file"); 2. ferror(): The ferror() function reports on the error state of the stream and returns true if an error has occurred. The function clears the end of file and error indicator for the argument stream. Library functions for error handling during file I/O operations:
  • 43. Syntax: ferror (FILE *file_pointer); • For example: • if(ferror(fp)!=0) • printf("An error has occurred"); • 3. perror(): • The perror() function displays the string we pass to it, followed by a colon, a space and then the textual representation of the current errno value. • Syntax: • void perror(const char *str); • The function displays a string giving error message as predefined in compiler for particular error condition. 4. strerror(): The strerror() function, returns a pointer to the textual representation of the current errno value. Syntax: strerror(int errno); 5.stderr: you should use stderr file stream to output all the errors.
  • 44. Program: Write a program for error handling. #include<stdio.h> #include<errno.h> #include<string.h> extern int errno; int main() { FILE * pf; int errnum; pf = fopen ("unexist.txt", "r"); if (pf == NULL) { errnum = errno; fprintf(stderr, "Value of errno: %dn", errno); perror("Error printed by perror"); fprintf(stderr, "Error opening file: %sn", strerror( errnum)); } else { fclose (pf); } return 0; } Output: Value of errno: 2 Error printed by perror: No such file or directory. Error opening file: No such file or directory.
  • 45. 5. Divide by Zero Error . There are some situations where nothing can be done to handle the error. In c language one such situation is division by zero. We can do is avoid doing this because if we do so, C language is not able to understand what happened, and gives a runtime error. Best way to avoid this is to check the value of the divisor before using it in the division operations. We can use if condition, and if it is found to be zero, just display a message and return from the function. It is a common problem that at the time of dividing any number, programmers do not check if a divisor is zero and finally it creates a runtime error The code below fixes this by checking if the divisor is zero before dividing.
  • 46. • Program: Write a program for divided by zero error. #include<stdio.h> #include<stdlib.h> void main() { int dividend = 2e; int divisor = 0; int quotient; if(divisor == 0) { fprintf(stderr, Division by zerol Exiting…n"); exit(-1); } quotient = dividend/divisory; fprintf(stderr, "Value of Quotient :%dn”,quotient); exit(0); } Output: Division by zero! Exiting…
  • 47. 6. Program Exit Status: We can also use Exit Status constants in the exit() function to inform the calling function about the error. The two constant values available for use, are EXIT_SUCCESS and EXIT FAILURE . These are nothing but macros defined <stdlib.h> header file. It is a common practice to exit with a value of EXIT_SUCCESS in case of program coming out after a successful operation. Here. EXIT_SUCCESS is a macro and it is defined as 0. If we have an error condition in our program and we are coming out then we should exit with a status EXIT_FAILURE which is defined as -1. So let's write above program as follows.
  • 48. • Program : Write a program for Exit status. #include<stdio.h> #include<stdlib.h> void main() { int dividend = 20; int divisor = 5; int quotient; if( divisor == 0) { fprintf(stderr, "Division by zero! Exiting... n"); exit(EXIT_FAILURE); } quotient = dividend / divisor; fprintf(stderr, "Value of quotient : %dn", quotient); exit(EXIT_SUCCESS); } Output: Value of quotient : 4
  • 49. Program : Write a program to indicate exit status. #include<stdio.h> #include<errno.h> #include<stdlib.h> #include<string.h> extern int errno; void main() { char *ptr=malloc(100000000UL); if(ptr==NULL) { puts("malloc failed"); puts(strerror(errno)); exit(EXIT_FAILURE); } else { free(ptr); exit(EXIT_SUCCESS); } } Explanation of program: Here exit function is used to indicate exit status. It is always a good practice to exit a program with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macros used to show exit status. In case of program coming out after a successful operation EXIT_SUCCESS is used to show successful exit. It is defined as O. EXIT_Failure is used in case of any failure in the program. It is defined as -1.
  • 50. • Program : Write a program for errors handling during file I/O operations. #include<stdio.h> #include<conio.h> void main(){ FILE *fp; clrscr(); fp=fopen("book.txt", “r"); if(fp==NULL){ printf("The file book.txt does not exist"); getch(); } fp=fopen("student.txt", "w"); if(fp==NULL) { printf("The read-only file students.txt cannot be opened in write mode"); getch(); } fp=fopen("text.txt","r"); fputc("a", fp); if(ferror(fp)) { printf("The file text.txt has been opened in read mode"); printf("but you are writing to it. n"); } getch(); } Output: The file book.txt does not exist The read-only file student.txt cannot opened in write mode The file text.txt has been opened in read mode but you are writing to it.
  • 51. RANDOM ACCESS FILE • Random Access files consist of records that can be accessed in any sequence. • This means the data is stored exactly as it appears in memory, thus saving processing time (because no translation is necessary) both in when the file is written and in when it is read. C standard library provides the following build-in functions to support this: 1. fseek() • The position fseek() repositions the file pointer. • The prototype of fseek() function is defined in stdio.h. • It is used to set the file position pointer for the given stream. The variable offset is an integer value that gives the number of bytes to move forward or backward in the file. The value of offset may be positive or negative, provided it makes sense. Syntax: fseek ( fp, offset, position); Where, fp is a pointer to FILE representing a file. offset is the number of bytes by which the file pointer is to be moved relative to the byte number identified by the third parameter position.
  • 52. • Position can take any one of the following three values 0,1 and 2. Table:fseek() options Position Symbolic_Constant Meaning 0 SEEK_SET Beginning of File 1 SEEK_CUR Current position of File 2 SEEK_END End of file Function Meaning feek(fp,0L,SEEK_SET); Moves to the beginning of the file fseek(fp,0L, SEEK_CUR); Stay at the current position of the file fseek(fp,0L, SEEK_END); Go to the End of File fseek(fp,m,SEEK_CUR); Move forward by m bytes in the file form the current location. fseek(fp,-m, SEEK_CUR); Moves backwards by m bytes in the file from the current location. fseek_(fp,-m,SEEK_END); Moves backwards by m bytes in the file from the end of the file
  • 53. 2. ftell() • The function ftell() returns the current position of the file pointer. • It is the position where the next input or output operation will be performed. • Syntax: position=ftell(fp); Where, fp is a pointer to FILE type representing a file, the current position of the file pointer of the file is returned be a function. • When using ftell(), errors can occur due to the following reasons: 1. Using ftell(), with a device that cannot store data(e.g. Keyboard) 2. When position is larger than that can be represented in a long integer. This will usually happen when dealing with very large files. • It is useful when we have to deal with text file for which position of the data cannot be calculated.
  • 54. Program 2.15: How to use ftell() Function in C. #include<stdio.h> #include<conio.h> void main() { FILE *fp; char c; int n; fp=fopen("abc.txt", "w"); if (fp==NULL) { printf("n error in opening file"); exit(1); } while((c=getchar()) !=EOF) putc(c, fp); n=ftell(fp); fclose(fp); fp=fopen("abc.txt","r"); if (fp==NULL) { printf("n error in opening file"); exit(1); } while(ftell(fp)<n) { c=fgetc(fp); printf("%c",c); } fclose(fp); getch(); }
  • 55. 3. rewind • The rewind positions the file pointer to the beginning of a file. • Syntax: rewind(fp); Program : Write a program for rewind(). #include<stdio.h> #include<conio.h> void main() { FILE * fp; char c; clrscr(); fp=fopen("file.txt", “r"); while((c=fgetc(fp))!=EOF) { printf("%c",c); } rewind(fp); while((c=fgetc(fp)) !=EOF) { printf("%c",c); } fclose(fp); getch(); } Output: This is a simple text this is a simple text.
  • 56. Program : Write a program to count the number of records in employee file. #include<stdio.h> #include<conio.h> struct emp { int empno; char name[20]; float salary; } void main() { FILE *fp; int nor, last_byte; clrscr(); fp=fopen("emp_dat","r"); last_byte=fseek(fp, 0, SEEK_END); nor=last_byte/sizeof(struct emp); printf("No. of records=%d", nor); fclose(fp); getch(); } Output: Number of records = 3
  • 57. 4. fgetpos(), fsetpos() • It is to get the current position in a file, or set the current position in a file. • It is just like ftell() and fseek() for most systems. • The fsetpos() function moves the file position associated with stream to a new location within the file according to the value of the object pointed to by pos. • The fgetpos() function stores the current value of the file pointer associated with stream into the object pointed to by pos. • Both the fgetpos() and fsetpos() function save state information for wide-oriented files. • The value stored in pos is unspecified, and it is usable only by fsetpos(). • Syntax: fsetpos (File *stream, fpos_t *pos); Where,The stream whose current position is to be determined. Pos is the current position of stream to be stored.
  • 58. • Program : Write a program for fgetpos() and fsetpos(). #include<stdio.h> int main() { FILE * fp; fpos_t position; fp = fopen("file.txt","w+"); fgetpos(fp, &position); fputs("Hello, students!", fp); fsetpos(fp, &position); fputs("Override previous contents...", fp); fclose(fp); return(0); } Output: Override previous contents...
  • 59. 5. remove(): • It is used to erase a file. • Syntax: remove(char *filename); Program : Write a program for remove file. #include<stdio.h> main() { remove("abc.txt"); return a; }
  • 60. COMMAND LINE ARGUMENTS • In C, it is possible to accept command line arguments. • Command line arguments are given after the name of a program in command line operating systems like DOS or Linux, and are passed in to the program from operating system. • To establish the data communication between a calling function and a called function. • It is done through arguments; a calling function passes inputs to a called function which perform required manipulations. • Declarations of command line in main function: • The main() can accept two arguments: • 1. The first argument is an integer value that specifies number of command line arguments. • 2. The second argument is a full list of all of the command line arguments. • Syntax: • int main(int argc, char *argv[]) • Here, argc and argv[] are the formal arguments, which provide mechanism for collecting the arguments given at command line when the program is launched for execution.
  • 61. Program 2.12:To write a program using command line arguments-Copying one file another file. #include<stdio.h> #include<conio.h> #include<process.h> void main(int arge, char *argv[ ]) { FILE *fin, *fout; char c; Clrscr; if(argc!=3) { printf("Invalid number of arguments"); exit(1); } fin=fopen(argv[1],"r"); fout=fopen(argv[2],"w"); while(!feof(fin)) { C=fgetc(fin); fputc(c, fout); } fclose(fin); fclose(fout); getch(); } o/p= c> copy text.txt text1.txt As a result, the contents of text.dat are copied to text1.txt
  • 62. Summary • Storage of information is read from or written on a auxiliary memory device is stored in the form of a file. • The data structure of a file is defined in stdio.h which creates a buffer area to store data in a file for reading as well as writing. • . fopen() is used to open a specified file. • fclose()is used to close a specified file. • fscanf() and fprintf() are used to perform input/output operation in files. • fgetc() and fputc) are used to perform character input/output operation in files. • fgets() and tputs() are used to perform string input/output operation in files, • getw() and putw() are used to write an integer value into a file and read integer value from a file. • fseek() is used to index a file and can be used to increment or decrement the filepointer. • rewind() is used to reset the file pointer to the beginning of the file. • file: The header file stdio.h defines a new data type called FILE. • stdio.h: Each file used in a program must be associated with a pointer of its type. Three types of file pointers are defined in stdio.h. They are stdin, stdout and stderr. • printf() and scanf(): printf() and scanf() are used for performing input/output operations in programs(without involving files). • fgetchar() and fputchar(): Character input/output functions which act on files. • feof(): The feof() function is used to check the end of file condition. •
  • 63. Trace the Output (1) What will be the output of following code? #include<stdio.h> int main() { FILE *fp=stdout; int n; fprintf(fp,"%dn ",45); fprintf(stderr, "%d ",65); return 0; } Output: 45 65. (4) What will be the output of the program? #include<stdio.h> int main() { FILE *ptr; char i; ptr = fopen("myfile.c", "r"); while((i=fgetc (ptr)) !=NULL) printf("%c", i); return 0; } Output: infinite loop.
  • 64. • (2) What will be the output of following code? • #include<stdio.h> • int main() • { • char c; • FILE * fp; • fp=fopen("demo.txt","r"); • while((c=fgetc(fp))! =E0F) • printf("%c",c); • fclose(fp); • return 0; • } • Output: It will print the content of file demo.txt. (3) What will be the output of the program? #include<stdio.h> int main() { FILE *fp1, *fp2; fp1=fopen("file.c", "w"); fp2=fopen("file.c", "w"); fputc('A', fp1); fputc('B',fp2); fclose(fp1); fclose(fp2); return 0; } Output: B.
  • 65. What will be the output of the program? #include<stdio.h> int main() { FILE *fp; char ch, str[7]; fp=fopen("try.c", "r");/* file 'try.c' contains "This is Nagpur" fseek(fp, 9L, SEEK_CUR); fgets(str, 5, fp); puts(str); return o; }