0% found this document useful (0 votes)
13 views28 pages

Files

Uploaded by

Haf hafeefa
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)
13 views28 pages

Files

Uploaded by

Haf hafeefa
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/ 28

FILES IN

C
Basics of Pointer: declaring pointers, accessing data though pointers,
N U L L pointer, array access using pointers, pass by reference effect.
File O perations: open, close, read, write, append.
Sequential access and random access to files: In built file handling
functions-
{rewind(), fseek(), ftell(), feof(), fread(), fwrite()}
Simple programs covering pointers and files.
Data Files

Data files allow us to store information permanently, and to access
and alter that information whenever necessary.

A data file can be treated as a collection of similar type of information
stored in a secondary storage.

C does not distinguish between sequential and direct access
(random access) data files.

There are two different types of data files in C :

stream-oriented (or standard) data files, and

system-oriented (or low-level) data files
Stream Oriented Data Files

Stream-oriented data files are generally easier to work with and are
therefore more commonly used.

Stream-oriented data files can be subdivided into two categories.

In the first category are text files, consisting of consecutive
characters.

These characters can be interpreted as individual data
items, or as components of strings or numbers.

The manner in which these characters are interpreted is
determined either by the particular library functions used to
transfer the information, or by format specifications within the
library functions
Stream Oriented Data Files

The second category of stream-oriented data files, often referred to as
unformatted data files, organizes data into blocks containing
contiguous bytes of information.

These blocks represent more complex data structures, such as
arrays and structures.

A separate set of library functions is available for processing
stream-oriented data files of this type.

These library functions provide single instructions that can
transfer entire arrays or structures to or from data files.
System Oriented Data Files

System-oriented data files are more closely related to the computer’s
operating system than stream-oriented data files.

They are somewhat more complicated to work with.

Their use may be more efficient for certain kinds of applications.

A separate set of procedures, with accompanying library functions, is
required to process system-oriented data files
Working with a Stream oriented data file in C

First step is to establish a buffer area, where information is
temporarily stored while being transferred between the computer’s
memory and the data file.

Declaring a file pointer :

FILE *ptvar;

where FILE (uppercase letters required) is a special structure type
defined in stdio.h file.

ptvar is a pointer variable that indicates the beginning of the
structure of type FILE.
Working with a Stream oriented data file in C

The structure type FILE is defined within a system include file,
typically stdio.h.

The pointer ptvar is often referred to as a stream pointer, or simply a
stream.
Opening a data file in C

A data file must be opened before it can be created or
processed.

This associates the file name with the buffer area (i.e., with
the stream).

It also specifies how the data file will be utilized,

as a read-only file,

A write-only file, or

a read-write file, in which both operations are permitted
Opening a data file in C

The library function fopen() is used to open a file.

This function is typically written as

ptvar = fopen( file-name, file-mode);

where file-name and file-mode are strings that represent the name of
the data file and the manner in which the data file will be utilized.

The name chosen for the file-name must be consistent with the rules
for naming files, as determined by the computer's operating system.
Opening a data file in C
Opening a data file in C

The fopen() function returns a pointer to the beginning of the
buffer area associated with the file.

A NULL value is returned if the file cannot be opened as, for example,
when an existing data file cannot be found.

This value can be used for checking whether the file is opened or
not.
Closing a data file in C

Finally, a data file must be closed at the end of the
program.

This can be accomplished with the library function
fclose().

fclose(ptva

The syntax
r); is

It is good programming practice to close a data file explicitly using
the fclose() function.

Most C compilers will automatically close a data file at the end
of program execution if a call to fclose() is not present.
Using data file in C
#include <stdio.h> #include
<stdio.h
void main() void main()
{ {
FILE *fptr; FILE
*fptr;
fptr = fopen(“Test.dat”, fptr = fopen(“Test.dat”,
“w”); “r”);
// writing data to the // Reading data from the
file. fclose(fptr); file. fclose(fptr);
}
}
Array Vs File
Array File
Stored in primary memory Stored in secondary memory
We have to specify the size of No such size specification is required.
the array.
All elements are of the same Similar type of information is stored in a
type. file.
Exists only during the Independent of the program
program execution time.

It can be used only within Files can be used by (or shared by)
the program in which it is different programs.
defined.
Processing a data file in C

Declare a file pointer

FILE *fp;

Create a link between the physical file and file
◆ pointer.
fp = fopen(filename, file-

Readmode);
from/ written into the file using appropriate library
functions.

Processing the data if required

◆ Closingfclose(ptva
the file
r);
Writing a character to a text file

Library function used is

putc(ch, fp);

Where ch is the charater to be written to the file and fp is the
file pointer.

In order to write information to the file, it must be opened in
“w” mode. [fp = fopen(filename, “w”) ]


You can also
use

fputc(ch, fp);
Reading a character from a text file

Library function used is

ch=getc(fp);

Where ch is the variable stores the charater read from the file and
fp is the file pointer.

In order to read information from the file, it must be opened in [fp
“r” mode. fopen(filename, “r”) ]. =

You can also
use


ch=fgetc(fp);
After each read, we have to check whether the end_of_file is
reached. One defined constant is used for this – EOF

Common usage is

while (( ch=getc(fp)) !=EOF)
{
Using data file in C
#include <stdio.h #include <stdio.h

void main() void main()


{ {
FILE FILE
*fp; *fptr;
char char ch;
ch; fptr = fopen(“Test.dat”,
fp = fopen(“Test.dat”, “r”); while
“w”); while ( (ch=getc(fp)) != EOF)
( (ch=getchar())!=EOF) putchar(c
} h);
putc(ch,
fp); fclose(fptr);
fclose(fp);

}
Writing to or Reading from - any item

Library function used is write is

fprintf(fp, “control_string”, item1, item2,...,itemn);

For example

fprintf(fp, “%5d%-20s%3d\n”, regno, name, mark);

Reading any item from text file
fscanf(fp, “control_string”, &var1, &var2,...,&varn);
For example
fscanf(fp, “%5d%20c%3d\n”, &regno, name, &mark);

After each read, we have to check whether the end_of_file is
reached. One defined constant is used for this – EOF

Common usage is

while ( fscanf(fp,”cs”,.....) !
=EOF) {
fgets() and fputs()

The fgets() function reads a sequence of character from an input
stream.

Its prototype is given below.
char * fgets(char *s , int n, FILE *fp);

The characters from the input stream are read into a character array
until a newline character is read, n–1 characters are read or the end-
of-file is reached.

If a newline character is read, it is retained in the character array.

The function then adds a terminating null character to strings and
returns it.

It returns a NULL value if an end-of-file is encountered before any
character is read or an error occurs during input.
fgets() and fputs()

The fputs() function writes a character string to an output stream.

Its format is given below.
int fputs(const char *s , FILE * fp) ;

All the characters in strings except the null terminator are written to
stream fp.

The function returns the numbers of characters written to the stream
or EOF if an error occurs during output.
fseek()

fseek() in C is used to change the file pointer (in order to point to a
specific file position) to the desired location.
int fseek(FILE *fp, long int offset, int from_where)
fp: It indicates the file object that is used to identify the file stream.
offset: It is defined in ‘long integer’ data type and is used to specify the
offset in terms of the number of bytes or characters where the position
indicator needs to be placed to define the new file position (+ve or -ve).
from_where: It defines the point where the file offset needs to be
added. In other terms, it defines the position where the file pointer
needs to be moved.
1 from begin (SEEK_SET)
2current position(SEEK_CUR)
2 – from end (SEEK_END)
ftell()

The ftell() returns the current file position of the specified stream with
respect to the starting of the file.

This function is used to get the total size of file after moving the file
pointer at the end of the file.

Prototype is :
long int ftell(FILE *stream);
rewind()

The rewind() function sets the file position to the beginning of the
file for the stream pointed to by stream.

It also clears the error and end-of-file indicators for stream.

Usage is :
void rewind(FILE *stream)
Unformatted file processing

Writing/Reading integers

putw(num, fp)

num=getw(fp)

Writing/Reading blocks of bytes

fwrite()

fwrite(address of item, size of item, number of items,
filepointer)

fread()

fread(address of item, size of item, number of items,
filepointer)
feof()

The C library function feof() tests the end-of-file indicator for the given
stream.

Usage is :
int feof(FILE *stream);

This function returns a non-zero value when End-of-File indicator
associated with the stream is set, else zero is returned.
Questions

Count the alphabets and digits in a text file.

Convert the characters of a text file to upper
case.

Count the lines, words and characters in a
text file.

You might also like