Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
25 views45 pages

File Handling in C

The document provides an overview of file handling in C, detailing typical operations such as opening, reading, writing, and closing files. It explains various functions and commands like fopen(), fclose(), fgetc(), fscanf(), and fwrite() for managing file input and output, along with examples of their usage. Additionally, it covers error handling and special streams like stdin, stdout, and stderr.

Uploaded by

jerry482891
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views45 pages

File Handling in C

The document provides an overview of file handling in C, detailing typical operations such as opening, reading, writing, and closing files. It explains various functions and commands like fopen(), fclose(), fgetc(), fscanf(), and fwrite() for managing file input and output, along with examples of their usage. Additionally, it covers error handling and special streams like stdin, stdout, and stderr.

Uploaded by

jerry482891
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

File Handling

1
Greater Noida Campus
Operations on Files

• Typical operations on a file are


• Open : To open a file to store/retrieve data in it

• Read : The file is used as an input

• Write : The file is used as output

• Close : Preserve the file for a later use

• Access: Random accessing data in a file

2
Greater Noida Campus

Opening and Closing a File

3
Greater Noida Campus
File Handling Commands
• Include header file <stdio.h> to access all file handling
utilities.
• A data type namely FILE is there to create a pointer to a file.
Syntax
FILE * fptr; // fptr is a pointer to file

• To open a file, use fopen() function


Syntax
FILE * fopen(char *filename, char *mode)

• To close a file, use fclose() function


Syntax
int fclose(FILE *fptr);

4
Greater Noida Campus
fopen() function

• The first argument is a string to characters indicating the name of


the file to be opened.
• The convention of file name should follow the convention of giving file
name in the operating system.

Examples:
xyz12.c student.data File PDS.txt

myFile

5
Greater Noida Campus
fopen() function
• The second argument is to specify the mode of file opening.
There are five file opening modes in C
• "r" : Opens a file for reading

• "w" : Creates a file for writing (overwrite, if it contains data)

• "a" : Opens a file for appending - writing on the end of the file

• “rb” : Read a binary file (read as bytes)

• “wb” : Write into a binary file (overwrite, if it contains data)

• It returns the special value NULL to indicate that it couldn't


open the file.
Lecture #07: © DSamanta CS 10001 : Programming and Data Structures 6
Greater Noida Campus
fopen() function
• If a file that does not exist is opened for writing or appending,
it is created as a new.
• Opening an existing file for writing causes the old contents to
be discarded.
• Opening an existing file for appending preserves the old
contents, and new contents will be added at the end.
• File opening error
• Trying to read a file that does not exist.
• Trying to read a file that doesn’t have permission.
• If there is an error, fopen() returns NULL.

Lecture #07: © DSamanta CS 10001 : Programming and Data Structures 7


Greater Noida Campus
Example: fopen()
#include <stdio.h>
void main()
{
FILE *fptr; // Declare a pointer to a file
char filename[]= "file2.dat";
fptr = fopen(filename,"w");
// Also, alternatively
// fptr = fopen (“file2.dat”,"w");
if (fptr == NULL) {
printf (“Error in creating file”);
exit(-1); // Quit the function
}
else /* code for doing something */
}

Lecture #07: © DSamanta CS 10001 : Programming and Data Structures 8


Greater Noida Campus

Reading from a File

9
Reading from a File
Greater Noida Campus

• Following functions in C (defined in stdio.h) are


usually used for reading simple data from a file
• fgetc(…)

• fscanf(…)

• fgets(…)

• getc(…)

• ungetc(…)

10
Reading from a File: fgetc()
Greater Noida Campus

Syntax for fgetc(…)


int fgetc(FILE *fptr)

• The fgetc() function returns the next character in the stream fptr as an
unsigned char (converted to int).

• It returns EOF if end of file or error occurs.

FILE *fptr;
int c;
/* Open file and check it is open */
while ((c = fgetc(fptr)) != NULL)
{
printf ("%c",c);
} 11
Reading from a File:
Greater Noida Campus
fscanf()

Syntax for fscanf(…)


int fscanf(FILE *fptr, char *format, ...);

• fscanf reads from the stream fptr under control of format and assigns
converted values through subsequent assignments, each of which must be a
pointer.
• It returns when format is exhausted.

• fscanf returns EOF if end of file or an error occurs before any conversion.

• it returns the number of input items converted and assigned.

12
Example: Using fscanf(…)
input.dat
FILE *fptr;
20 30 40 50
fptr= fopen (“input.dat”,“r”);
int n;
/* Check it's open */
if (fptr == NULL)
{
printf(“Error in opening file \n”);
}
x = 20
x = 30
n = fscanf(fptr,“%d %d”,&x,&y);

...

13
Reading from a File:
Greater Noida Campus
fgets(…)

Syntax for fgets(…)


char *fgets(char *s, int n, FILE *fptr)
s The array where the characters that are read will be stored.
n The size of s.
fptr The stream to read.

• fgets() reads at most n-1 characters into the array s, stopping if a


newline is encountered.
• The newline is included in the array, which is terminated by ‘\0’.

• The fgets() function returns s or NULL if EOF or error occurs.

14
Greater Noida Campus
Example: Using fgets(…)

FILE *fptr;
char line [1000];
/* Open file and check it is open */

while (fgets(line,1000,fptr) != NULL)


{
printf ("Read line %s\n",line);
}

15
Reading a File: getc(…)
Greater Noida Campus

Syntax for getc(…)


int getc(FILE *fptr)
• getc(…) is equivalent to fgetc(…) except that it is a macro.

16
Example: Using getc(…)
C program to read a text file and then print the content on the screen.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ch, fileName[25];
FILE *fp;
printf("Enter the name of file you wish to read\n");
gets(fileName);
fp = fopen(fileName,"r"); // read mode

if( fp == NULL )
{
printf("Error while opening the file.\n");
exit(-1);
}
OUTPUT
printf("The contents of %s file are :\n", fileName);
while( ( ch = getc(fp) ) != EOF )
Enter the name of file you wish to read
printf("%c",ch);
test.txt
fclose(fp); The contents of test.txt file are :
return 0; C programming is fun.
}

17
Undo a File Reading:
Greater Noida Campus ungetc()

ungetc(): Push a character back onto an input stream.


Syntax:
int ungetc(int c, FILE *fptr)
Arguments:
c The character that you want to push back.
fptr The stream you want to push the character back on.
• Only one character of pushback is guaranteed per file.
• ungetc may be used with any of the input functions like
scanf, getc, or getchar.
18
Example: ungetc()
Greater Noida Campus

#include <stdio.h>
int main(void)
{ OUTPUT
int ch;
a
while ((ch = getchar()) != '1') // reads characters from the stdin a
putchar(ch); // and show them on stdout until encounters
v '1'
v
ungetc(ch, stdin); // ungetc() returns '1' previously read back to stdin
c
c
ch = getchar(); // getchar() attempts to read next character from stdin
u
// and reads character '1' returned back to the stdin by ungetc()
u
putchar(ch); // putchar() displays character 1
puts(""); 1
Thank you!
printf("Thank you!\n");
return 0;
}

19
Greater Noida Campus

Writing into a File

20
Greater Noida Campus Writing into a File
• Following functions in C (defined in stdio.h) are usually used
for writing simple data into a file
• fputc(…)

• fprintf(…)

• fputs(…)

• putc(…)

21
Writing into a File:
Greater Noida Campus
fputc(…)
Syntax for fputc(…)
int fputc(int c, FILE *fptr)

• The fputc() function writes the character c to file fptr and returns the
character#include <stdio.h>
written, or EOF if an error occurs.

filecopy(File *fpIn, FILE *fpOut)

{
int c;

while ((c = fgetc(fpIn) != EOF)


fputc(c, fpOut);
}
22
Writing into a File:
Greater Noida Campus
fprintf(…)
Syntax for fprintf(…)
int fprintf(FILE *fptr, char *format,...)
• fprintf() converts and writes output to the steam fptr under the control
of format.

• The function is similar to printf() function except the first argument


which is a file pointer that specifies the file to be written.

• The fprintf() returns the number of characters written, or negative if an


error occur.

23
Writing into a File:
Greater Noida Campus
fprintf(…)
#include <stdio.h>

void main()

{
FILE *fptr;
fptr = fopen(“test.txt”, “w”);

fprintf(fptr, “Programming in C is really a fun!\n”);


fprintf(fptr, “Let’s enjoy it\n”);

fclose(fptr);

return;
}

24
Writing into a File:
Greater Noida Campus
fputs()
Syntax for fputs:
int fputs(char *s, FILE *fptr)

• The fputs() function writes a string (which need not contain a newline) to
a file.

• It returns non-negative, or EOF if an error occurs.

25
Example: fputs(…)
Greater Noida
#include Campus
<stdio.h>

void main()

{
FILE *fptr;
fptr = fopen(“test.txt”, “w”);

fputs(“Programming in C is really a fun!”, fptr);


fputs(“\n”, fptr);
fputs(“Let’s enjoy it \n”, fptr);

fclose(fptr);

return;
}

26
Writing into a File:
Greater Noida Campus
putc(…)
Syntax for putc(…)
int putc(FILE *fptr)

• The putc() function is same as the putc(…).


#include <stdio.h>

filecopy(File *fpIn, FILE *fpOut)

{
int c;

while ((c = getc(fpIn) != EOF)


putc(c, fpOut);
}
27
Greater Noida Campus
Writing into a File: Example
• A sample C program to write some text reading from the
keyboard and writing them into a file and then print the content
from the file<stdio.h>
#include on the screen.

main()

{
FILE *f1;

char c;

printf("Data Input\n\n");
/* Open the file INPUT */
Contd…
f1 = fopen("INPUT", "w");

28
Greater Noida Campus
Writing into a File
while((c=getchar()) != EOF) /* Get a character from keyboard*/
OUTPUT
putc(c,f1); /* Write a character to INPUT*/
Data Input

fclose(f1); /* Close the file INPUT*/ This is a program to test


printf("\nData Output\n\n"); the file handling features on
this system
f1 = fopen("INPUT","r"); /* Reopen the file INPUT */
Data Output
while((c=getc(f1)) != EOF) /* Read a character from INPUT*/
printf("%c",c); /* Display a character on screen */
This is a program to test
fclose(f1); /* Close the file INPUT */ the file handling features on
this system
}

29
Greater Noida Campus

Special Streams in C

30
Greater Noida Campus
Special Streams
• When a C program is started, the operating system environment is
responsible for opening three files and providing file pointer for
them. These files are

• stdin Standard input. Normally it is connected to keyboard

• stdout Standard output, In general, it is connected to display


screen

• stderr It is also an output stream and usually assigned to a


program in
the same way that stdin and stderr are. Output written on
stderr normally appears on the screen

Note:
getc(stdin) is same as fgetc (stdin)
31
Special Streams
Greater Noida Campus

fprintf (stdout,"Hello World!\n");

printf(“"Hello World!\n");

The above two statements are same!

32
Example: Special Streams
Greater Noida Campus
#include <stdio.h>
main()
{
int i;

fprintf(stdout,"Give value of i \n");


fscanf(stdin,"%d",&i);
fprintf(stdout,"Value of i=%d \n",i);

OUTPUT
Give value of i
15
Value of i=15

33
Error Handling : stderr and exit
• What happens if the errors are not shown in the screen instead
if it's going into a file or into another program via a pipeline.
• To handle this situation better, a second output stream, called
stderr, is assigned to a program in the same way that
stdin and stdout are.
• Output written on stderr normally appears on the screen
even if the standard output is redirected.

34
Example: Error Handling

#include <stdio.h>

/* cat: concatenate files */


main(int argc, char *argv[])
{
FILE *fp;
void filecopy(FILE *, FILE *);
char *prog = argv[0]; /* program name for errors */

if (argc == 1 ) /* no args; copy standard input */


filecopy(stdin, stdout);
else
while (--argc > 0)

Contd…
35
Example: Error Handling

if ((fp = fopen(*++argv, "r")) == NULL) {


fprintf(stderr, "%s: can't open %s\n", prog, *argv);
exit(1);
} else {
filecopy(fp, stdout);
fclose(fp);
}

if (ferror(stdout)) {
fprintf(stderr, "%s: error writing stdout\n", prog);
exit(2);
}
exit(0);
}

36
Direct Input and Output

37
Structured Input/Output for Files
• Other than the simple data, C language provides the following
two functions for storing and retrieving composite data.

• fwrite() To write a group of structured data

• fread() To read a group of structured data

38
Writing Records: fwrite()
fwrite() writes data from the array pointed to, by ptr to the
given stream fptr.
Syntax:

int fwrite(void *ptr, int size, int nobj, FILE *fptr);

• ptr This is the pointer to a block of memory with a minimum size of


size *nobj bytes.
• size This is the size in bytes of each element to be written.
• nobj This is the number of elements, each one with a size of size bytes.
• fptr This is the pointer to a FILE object that specifies an output stream.

39
Example: fwrite()
#include<stdio.h>

struct Student
{
int roll;
char name[25];
float marks;
};

void main()
{
FILE *fp;
int ch;
struct Student Stu;

fp = fopen("Student.dat","w"); //Statement 1

if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
Contd…
40
Example: fwrite()
do
{
printf("\nEnter Roll : ");
scanf("%d",&Stu.roll);

printf("Enter Name : ");


scanf("%s",Stu.name);

printf("Enter Marks : ");


scanf("%f",&Stu.marks);

fwrite(&Stu,sizeof(Stu),1,fp);

printf("\nDo you want to add another data (y/n) : ");


ch = getchar();

}while(ch=='y' || ch=='Y');

printf("\nData written successfully...");

fclose(fp);
}

Contd…
41
Example: fwrite()
OUTPUT

Enter Roll : 1
Enter Name : AA
Enter Marks : 78.53
Do you want to add another data (y/n) : y

Enter Roll : 2
Enter Name : BB
Enter Marks : 72.65
Do you want to add another data (y/n) : y

Enter Roll : 3
Enter Name : CC
Enter Marks : 82.65
Do you want to add another data (y/n) : n

Data written successfully...

42
Reading Records: fread()
fread() reads data from the given stream into the array pointed
to, by ptr.
Syntax:

int fread(void *ptr, int size, int nobj, FILE *fptr);

• ptr This is the pointer to a block of memory with a minimum size of


size *nobj bytes.
• size This is the size in bytes of each element to be read.
• nobj This is the number of elements, each one with a size of size bytes.
• fptr This is the pointer to a FILE object that specifies an input stream.

43
Example: fread()
#include<stdio.h>

struct Student
{
int roll;
char name[25];
float marks;
};

void main()
{
FILE *fp;
int ch;
struct Student Stu;

fp = fopen("Student.dat","r"); //Statement 1

if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}

Contd…
44
Example: fread()
printf("\n\tRoll\tName\tMarks\n");

while(fread(&Stu,sizeof(Stu),1,fp)>0)
printf("\n\t%d\t%s\t
%f",Stu.roll,Stu.name,Stu.marks);

fclose(fp);
}

OUTPUT

Roll Name Marks


1 AA 78.53
2 BB 72.65
3 CC 82.65

45

You might also like