0% found this document useful (0 votes)
6 views66 pages

problem solving using c full course paart 3

Unit 6 covers the concept of files in programming, including file operations, file types, and standard library I/O functions. It explains the need for files to manage large data efficiently and introduces file handling functions such as fopen, fclose, fscanf, and fprintf. The unit also discusses file modes, buffers, and streams, providing practical examples for reading and writing data to files.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views66 pages

problem solving using c full course paart 3

Unit 6 covers the concept of files in programming, including file operations, file types, and standard library I/O functions. It explains the need for files to manage large data efficiently and introduces file handling functions such as fopen, fclose, fscanf, and fprintf. The unit also discusses file modes, buffers, and streams, providing practical examples for reading and writing data to files.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 66

Unit-6

K.Vigneswara Reddy, Dept. of I.T


• Include directories
c:\tc\Include\
• Library directories
c:\tc\lib;c:\tc\classlib\lib
• Output directory
c:\tc\bin
• Source directories
c:\tc\bin
K.Vigneswara Reddy, Dept. of I.T
Topics to be covered in Unit 6

Files – Concept of File, file information table,


streams, text and binary streams, stream file
processing, system created steams,
Standard library I/O functions, file open and
close, Formatting I/O functions,
Character I/O functions,
Binary I/O,
Command line arguments
File status functions, positioning functions

K.Vigneswara Reddy, Dept. of I.T


FILES
Files – File name, file information table, streams,
text and binary streams, stream file processing,
system created steams.
Standard library I/O functions, file open and close,
Formatting I/O functions, Character I/O functions,
Binary I/O, Standard library functions.

K.Vigneswara Reddy, Dept. of I.T


Need of files
• Scanf and printf functions are used to read and write
the data through terminals.
• This is fine as long as the data is small.
• When data is large, it is time consuming to handle the
data through terminals.
• The entire data is lost when the program is
terminated or the computer is turned off.
• It is necessary to maintain the data in a manner that
could be retrieved or used whenever needed.

K.Vigneswara Reddy, Dept. of I.T


files
 A file is an external collection of related data treated as a
unit.
 The primary purpose of a file is to keep record of data.
 Record is a group of related fields. Field is a group of
characters they convey meaning.
 Files are stored in auxiliary or secondary storage devices.
The two common forms of secondary storage are disk
(hard disk, CD and DVD) and tape.
 Each file ends with an end of file (EOF) at a specified
byte number, recorded in file structure.
 A file must first be opened properly before it can be
accessed for reading or writing. When a file is opened an
object (buffer) is created and a stream is associated with
the object K.Vigneswara Reddy, Dept. of I.T
FILE NAME:

File name is a string of characters that make up a valid filename.

Every operating system uses a set of rules for naming its files.

When we want to read or write files, we must use the operating


system rules when we name a file.

The file name may contain two parts, a primary name and an optional
period with extension.

Example: input.txt
program.c

K.Vigneswara Reddy, Dept. of I.T


7
FILE INFORMATION TABLE:

A program that reads or write files needs to know several


pieces of information, such as name of the file, the
position of the current character in the file ,size, type
and so on.

C has predefined structure to hold this information.

The stdio.h header file defines this file structure; its


name is FILE

When we need a file in our program, we declare it using


the FILE type.

K.Vigneswara Reddy, Dept. of I.T


8
BUFFER/ STREAM

 When the computer reads, the data move from


the external device to memory; when it writes,
the data move from memory to the external
device. This data movement often uses a special
work area known as buffer.
 A buffer is a temporary storage area that
holds data while they are being transferred to
or from memory.
 The primary purpose of a buffer is to
synchronize the physical devices(keyboard,
monitor) with a program's need.
K.Vigneswara Reddy, Dept. of I.T
STREAM:
 A stream is a source or destination of the data, it is associated
with a physical device such as terminals (keyboard, monitor) or
with a file stored in memory.

 C has two forms of streams: Text Stream and Binary Stream.


 A text stream consists of a sequence of characters divided into
lines with each line terminated by a new line (\n).

 A binary stream consists of sequence of data values such as


integer, real, or complex using their memory representation.

 A terminal keyboard and monitor can be associated only with a


text stream. A keyboard is a source for a text stream; a monitor
is a destination for a text stream.

K.Vigneswara Reddy, Dept. of I.T


K.Vigneswara Reddy, Dept. of I.T
11
System Created Streams:

C provides standard streams to communicate with a terminal.

The first, stdin, points to the standard input stream which is


normally connected to the keyboard.

The second, stdout, points to the standard output stream


which is normally connected to the monitor.

The third, points to the standard error stream which is also


normally connected to the monitor.

There is no need to open and close the standard streams. It


is done automatically by the operating system.

K.Vigneswara Reddy, Dept. of I.T


12
STREAM FILE PROCESSING:

A file exists as an independent entity with a name known to the


O.S.

A stream is an entity created by the program.

To use a file in our program, we must associate the program’s


stream name with the file name.

In general, there are four steps to processing a file.


1. Create a stream
2. Open a file
3. Process the file (read or write data)
4. Close a file
K.Vigneswara Reddy, Dept. of I.T
13
Creating a Stream:
We can create a stream when we declare it.

The declaration uses the FILE type as shown below:


FILE *spData;

The FILE type is a structure that contains the information needed


for reading and writing a file and spData is a pointer to the
stream.
Opening a File:
Once stream has been created, we can ready to associate the stream
to a file. This is done through open function.

When the file is opened, the stream and the file are associated with
each other.

Closing the Stream:


When file processing is complete, we close the file. After closing the
file The stream is no longer available.

K.Vigneswara Reddy, Dept. of I.T


14
File Operations
• Several operations are applied on the files.
1. creation a file
2. opening an existing file
3. reading from a file
4. closing a file.
5. writing to a file.
6. copying a file.
7. moving to a desired location in a file.

K.Vigneswara Reddy, Dept. of I.T


1.Creation of a file
• File name as “abc.c” and write some data in the file and
save in your folder then it permanently stored on to the disk.
• Abc.c

K.Vigneswara Reddy, Dept. of I.T


2. Open a file
 Before read or write data from or to a file on a disk we must open the file
using the function fopen() .
 it takes two arguments
1. file name which is to be opened
2. mode of a file whether it is read or write
fopen() performs three tasks
1. searches file on a disk which is to be opened
2. loads the file from disk to memory called buffer (temporary memory)
3. sets a character pointer that points to the first character of the buffer.
What is the need of buffer at all?
When we want to read a character from the file every time we need to access
the disk it takes the more time for the disk drive to position the read/write
head correctly.
- Read the file character by character from the buffer is efficient rather than
from disk.

K.Vigneswara Reddy, Dept. of I.T


• To open a file, we need to specify the physical
filename and its mode.
• Syntax
fopen (“filename”, “mode”);

• fopen() returns the address of the first


character of the buffer which is collected in the
structure pointer called fp.
• Hence we declared as
FILE *fp;
FILE structure is defined in the header file
“stdio.h”.
K.Vigneswara Reddy, Dept. of I.T
File opening modes
while creating a file we are also specifying the purpose of opening this
file. The modes does this job.
1. “r” (read mode)- searches for the file. If file exist on disk,
brought into the memory and sets the pointer points to the first
character in the memory. If file does not exist returns the NULL.
syntax fopen(“filename”,”r”);
operation- reading the file.
2. “w” (write mode) - searches for the file. if file exist overwrite its
contents. If not create a new file . If space is not available on the
disk returns the NULL.
syntax fopen(“filename”,”w”);
operation- writing to a file.
3. “a” ( append mode) - searches file. If file already exist it returns
the pointer points to last character in the file. The new data is
added at the end of the file.
If the file doesn’t exist, it is created and opened. In this case,
the writing will start at the beginning of the file.
syntax fopen(“filename”,”a”);
operation- adding new contents to the end of the file.
K.Vigneswara Reddy, Dept. of I.T
4. “r+” ( read and write mode) - same as r mode. If file does not exist it
returns NULL.
Syntax: fopen (“filename”,”r+”);
operations are different – reading, writing new contents and modifying
the existing contents of the file.
5. “w+”-(write and read) writing new contents, reading them back and
modifying the existing contents of the file. If a file already exists its
contents erased. If a file does not exist then new file created.
Syntax: fopen (“filename”,”w+”);
6. “a+” (append and read) - reading existing contents, appending new
contents at the end of the file and cannot modify the existing content
of the file.
syntax: fopen(“filename”,”a+);

K.Vigneswara Reddy, Dept. of I.T


File Modes
K.Vigneswara Reddy, Dept. of I.T
Program for check whether the file is
exist or not
void main()
{
FILE *fp;
fp=fopen(“abc.r”,”r”);
if(fp= =NULL)
{
puts(“ file does not exist\n”);
exit();
}//if
}//main

K.Vigneswara Reddy, Dept. of I.T


4. Closing a file
• When we have finished with the open
file, we need to close it using fclose()
syntax fclose(file pointer);
this would perform three operations
1. file would be again written on to disk
2. buffer would be eliminated.

K.Vigneswara Reddy, Dept. of I.T


STANDARD LIBRARY I/O FUNCTIONS:

C includes many standard functions to input data from the keyword and
output data to the monitor.

The stdio.h header file contains several different input/output functions


declarations.

These are grouped into eight different categories.

K.Vigneswara Reddy, Dept. of I.T


24
K.Vigneswara Reddy, Dept. of I.T
25
FORMATED I/O FUNCTIONS:

We have already familiar with two formatting functions scanf and
printf.
These two functions can be used only with the keyboard and
monitor.

The C library defines two more general functions, fscanf and


fprintf, that can be used with any text stream.

K.Vigneswara Reddy, Dept. of I.T


26
Reading from Files: fscanf ()
It is used to read data from a user-specified stream.(files)

The general format of fscanf() is:


fscanf (stream_pointer, ”format string”, list);

The first argument is the stream pointer, it is the pointer to the


streams that has been declared and associated with a text file.
Remaining is same as scanf function arguments.

The following example illustrates the use of an input stream.


int a, b;
FILE *fptr1;
fptr1 = fopen (“mydata", "r”);
fscanf (fptr1, "%d %d", &a, &b);

The fscanf function would read values from the file "pointed" to
by fptr1 and assign those values to a and b.
K.Vigneswara Reddy, Dept. of I.T
27
Writing to Files: fprintf ()
It can handle a group of mixed data simultaneously.

The first argument of these functions is a file pointer which


specifies the file to be used.

The general form of fprintf is:


fprintf (stream_pointer, ”format string”, list);

Where stream_pointer is a file pointer associated with a file


that has been opened for writing.

The format string contains output specifications for the items


in the list.

The list may include variables, constants and strings.


K.Vigneswara Reddy, Dept. of I.T
28
The following example illustrates the use of an Output stream.
int a = 5, b = 20;
FILE *fptr2;
fptr2 = fopen (“results", "w”);
fprintf (fptr2, "%d %d\n", a, b) ;

The fprintf functions would write the values stored in a and b


to the file "pointed" to by fptr2.

fprintf function works like printf except that it specifies the


file in which the data will be displayed.

K.Vigneswara Reddy, Dept. of I.T


29
Writes record of a students to a
file
#include<stdio.h>
using structure
struct student
{
char name[30];
int rollno;
float marks;
};
void main()
{
FILE *fp;
struct student s;
fp=fopen("abc.c","w");
printf("\n enter name rollno and marks of a student\n");
scanf("%s %d %f",s.name,&s.rollno,&s.marks);
fprintf(fp,”%s\nr %d\n%f\n",s.name,s.rollno,s.marks);
fclose(fp);
}//main

K.Vigneswara Reddy, Dept. of I.T


Reading records from a file
fscanf()- used to read the structure from a file
general form- fscanf(fp,”control string”,&var1,&var2….);
#include<stdio.h>
struct student
{
char name[30];
int rollno;
float marks;
};
void main()
{
FILE *fp;
struct student s;
fp=fopen("abc.c","r");
while(fscanf(fp,"%s %d %f",s.name,&s.rollno,&s.marks)!=EOF)
printf("%s\n %d\n%f\n",s.name,s.rollno,s.marks);
fclose(fp);
}//main

K.Vigneswara Reddy, Dept. of I.T


CHARACTER I/O FUNCTIONS:
Character input functions read one character at a time from a text
stream.
Character output functions write one character at the time to a text
stream.

These functions can be divided into two categories:


Terminal Character I/O, Terminal and File Character I/O
Character I/O

Terminal Only Any Stream

Input Output Input Output

getchar putchar getc / fgetc putc / fputc


32
K.Vigneswara Reddy, Dept. of I.T
TERMINAL CHARACTER I/O:
C declares a set of character input/output functions that can only be used
with the standard streams:
standard input (stdin), standard output (stdout).

Read a character: getchar ()


It reads the next character from the standard input stream and return its
value.
Syntax: int getchar (void);

Its return value is integer. Up on successful reading returns the ASCII


value of character otherwise it returns EOF.

Write a character: putchar ()


It writes one character to the monitor.
Syntax: int putchar (int ch);

Its return value is integer. Up on successful writing returns the ASCII value
of character. Otherwise returns EOF.

K.Vigneswara Reddy, Dept. of I.T


33
TERMINAL AND FILE CHARACTER I/O :

The terminal character input/output functions are designed for


convenience; we don’t need to specify the stream.

Here, we can use a more general set of functions that can be


used with both the standard streams and a file.

These functions require an argument that specifies the stream


associated with a terminal device or a file.

When used with a terminal device, the streams are declared


and opened by the system, the standard input stream (stdin)
for the keyword and standard output stream (stdout) for the
monitor.

When used with a file, we need to explicitly declare the stream,


it is our responsibility to open the stream and associate with
the file. K.Vigneswara Reddy, Dept. of I.T
34
Read a character: getc () and fgetc ()

The getc functions read the next character from the stream,
which can be a user-defined stream or stdin, and converts it in
to an integer.

This function has one argument which is the file pointer


declared as FILE or stdin (in case of standard input stream).

If the read detects an end of file, the function returns EOF,


EOF is also returned if any error occurs.

The functionality of getc / fgetc is same.

Syntax:
int getc (FILE *spIn); or int getc(stdin);
int fgetc (FILE *spIn); or int fgetc(stdin);

K.Vigneswara Reddy, Dept. of I.T


35
Write a Character: putc () and fputc ()
The putc function writes a character to the stream which can
be a user-defined stream, stdout, or stderr.

The functionality of putc/ fputc is same.

The functions, putc or fputc takes two arguments.

The first parameter is the character to be written and the


second parameter is the file.

The second parameter is the file pointer declared as FILE or


stdout or stderr.

If the character is successfully written, the function returns


it. If any error occurs, it returns EOF.
Syntax:
int putc (char, *fp);
int fputcK.Vigneswara
(char, *fp);
Reddy, Dept. of I.T
36
Reading from a file-fgetc()
• To read the contents of a file there
exists a function called fgetc().
• This function reads the character from
the current pointer position, advances
the pointer to next position and
returns the character that is read.

K.Vigneswara Reddy, Dept. of I.T


Write a program to read the contents of the file and
display them on console
readf.c

• #include<stdio.h>
void main()
{
FILE *fp;
Char c;
fp=fopen(“readf.c”,”r”);
while((c=fgetc(fp))!=EOF)
printf(“%c”,c); •While loop would be exit when it reaches to
fclose(fp); the EOF which is special character of
}//main ascii value 26 placed beyond the last
character of the file, when the file is created.

•EOF is macro defined in the file stdio.h

K.Vigneswara Reddy, Dept. of I.T


Writing characters on to a file

• To write characters on to a file use the


function fputc() or putc().
• It takes two arguments
1. character to be write on to a file
2. file pointer which points a file

K.Vigneswara Reddy, Dept. of I.T


Writing contents on to a file
#include<stdio.h>
void main()
{ // read the contents of a file again
FILE *fp; printf("display the contents of a file
char c; abc.c\n");
// write contents on to a file fp= fopen("abc.c","r");
printf("open a file abc.c\n"); while((c=fgetc(fp)!=EOF)
fp= fopen("abc.c","w"); printf("%c",c);
while( (c=getchar())!=EOF) fclose(fp);
fputc(c,fp); }//main
fclose(fp);

K.Vigneswara Reddy, Dept. of I.T


Write a program to copy the contents of one file
to other file.
fw=fopen("xyz.c","w");
#include<stdio.h> if(fw==NULL)
#include<stdlib.h> {
void main() puts("no space in memory cannot be opened");
{ fclose(fw);
exit(0);
FILE *fr,*fw;
}//if
char c; while((c=fgetc(fr)!=EOF)
fr=fopen("abc.c","r"); fputc(c,fw);
if(fr==NULL) }//while
{ fclose(fr);
fclose(fw);
puts("file does not exist");
}//main
exit(0);
}//if

K.Vigneswara Reddy, Dept. of I.T


Example illustrating counting characters,tabs,space,…from a file
#include<stdio.h> if(c==' '||c=='\t'||c=='\n')
#include<stdlib.h> now++;
void main() if(c=='\n')
{FILE *fr; nol++;
char c; }//while
int nol=0,nos=0,not=0,noc=0,now=0; fclose(fr);
fr=fopen("countingf.c","r"); printf("\n the no of characters=%d",noc);
while((c=fgetc(fr))!=EOF) printf("\n the no of spaces=%d",nos);
if(c!='\n') printf("\n the no of tabs=%d",not);
noc++; printf("\n the no of words=%d",now);
if(c==' ') printf("\n the no of lines=%d",nol);
nos++; getch();
if(c=='\t') }//main
not++;

K.Vigneswara Reddy, Dept. of I.T


Text and binary files
• All the programs what we have done so far
called text files in which characters ,strings
,and numbers are stored in the ascii codes
that file is text file.
• A binary file is a collection of bytes. It is a
compiled version of c program like .exe file.

K.Vigneswara Reddy, Dept. of I.T


TEXT FILES AND BINARY FILES:
Text File: It is a file in which data are stored using only characters; a text file is
written using text stream.
Non-character data types are converted to a sequence of characters before they are
stored in the file.

In the text format, data are organized into lines, terminated by newline character.
The text files are in human readable form and they can be created and read using any
text editor.

Text files are read and written using input / output functions that convert characters
to data types: scanf and printf, getchar and putchar, fgets and fputs.

The following figure shows the data transfer in text file:

K.Vigneswara Reddy, Dept. of I.T


Reading and Writing Text Files 44
Binary File:
A binary file is a collection of data stored in the internal format of
the computer.

The binary files are not in human readable form.

There are no lines or newline characters.

Binary files are read and written using binary streams known as block
input / output functions.

The following figure shows the data transfer in binary file:

K.Vigneswara Reddy, Dept. of I.T


Block Input and Output 45
Differences between Text File and Binary File

Text File Binary File


Data is stored as lines of Data is stored on the disk in the
characters with each line same way as it is represented in
terminated by newline. the computer memory.
Human readable format. Not in human readable format.
There is a special character called There is an end-of-file marker.
end-of-file(EOF) marker at the
end of the file.
Data can be read using any of the Data can be read only by specific
text editors. programs written for them.

K.Vigneswara Reddy, Dept. of I.T


Opening Binary Files
The basic operation is unchanged for binary files, only the mode changes.

Just like text files, binary files must be closed when they are not needed
anymore using fclose ().

Mode Meaning
This mode opens a binary file in write mode.
wb
Example: fp=fopen (“data.dat”,”wb”);
This mode opens a binary file in read mode.
rb
Example: fp=fopen (“data.dat”,”rb”);
This mode opens a binary file in append mode.
ab
Example: fp=fopen (“data.dat”,”ab”);
This mode opens/creates a binary file in write and read mode.
w+b
Example: fp=fopen (“data.dat”,”w+b”);
This mode opens a pre-existing binary file in read and write mode.
r+b
Example: fp=fopen (“data.dat”,”r+b”);
This mode opens/creates a binary file in append mode.
a+b
Example: fp=fopen (“data.dat”,”a+b”);
K.Vigneswara Reddy, Dept. of I.T
Binary Modes of Opened File
BLOCK I/O FUNCTIONS:

C language uses the block input and output functions to read and write
data of binary files.

As we know that data are stored in memory in the form of 0’s and 1’s.

When we read and write the binary files, the data are transferred
just as they are found in memory and hence there are no format
conversions.

The block read function is file read(fread) and the block write
function is file write (fwrite).

K.Vigneswara Reddy, Dept. of I.T


48
• To write the records on to a binary file use library function fwrite()
• fwrite() takes 4 arguments
syntax

fwrite (&structure variable,sizeof(structure variable),no.of records to be


write at time,file pointer);

To read the records from a file use fread with four arguments .
fread (&structure variable,sizeof(structure variable),no.of records to be
read at a time,file pointer);

K.Vigneswara Reddy, Dept. of I.T


/* write a c program to write and read a student record by using
fwrite() and fread()*/
#include<stdio.h>
Struct student{
Char name[30];
int rollno;
float marks;
}s;
void main(){
FILE *fptr;
fptr=fopen(“student.dat”,”wb+”);
Printf(“enter student details”);
scanf(“%s %d %f”,s.name,&s.rollno,&s.marks);
fwrite(&s,sizeof(s),1,fptr);
fread(&s,sizeof(s),1,fptr);
printf(“\n student name=%s”,s.name);
printf(“\n student rollno=%d”,s.rollno);
printf(“\n student marks=%f”,s.marks);
K.Vigneswara Reddy, Dept. of I.T
fclose(fptr);}//main
Command line arguments
• Passing parameters to the main function is called
command line arguments.
• It is also supplying the parameters to a program when
the program is running.
• If we want to copying the one file to another file use
the command as
c> ./a.out abc.data xyz.data.
• Main function also takes two arguments called argc
and argv the information contained in the command
line is passed on to the program through these
arguments.

K.Vigneswara Reddy, Dept. of I.T


• argc- no of arguments passing to a program
when the program is running.
• argv()- it is an array of pointers to strings.
• When the program is executed, the strings on
the command line are passed to main()
• Ex- ./a.out abc.data xyx.data
Then
argc would contains 3
argv[0]- base address of the string “./a.out”
argv[1]- base address of the string “abc.data”
argv[2]- base address of the string “xyz.data”.
K.Vigneswara Reddy, Dept. of I.T
Copy content of one file to another file using command line arguments
void main(int argc,char *argv[])
{
FILE *fp; How to execute this command line arguments
Char ch; program
FILE *fp1,*fp2;
fp1= fopen(argv[1],”r”); To compile cc filename.c
fp2= fopen(argv[2],”w”);
if(fp1) To execute .\a.out inputfilename outputfilename
{
While(( ch=getc(fp1))!= EOF)
{
putc(ch,fp2);
}//while
}//if
else
printf(“file does not exist”);
fclose(fp1);
fclose{fp2); K.Vigneswara Reddy, Dept. of I.T
• /* write c c program to create a file by command line argument and add
text given by the user to that file and open the file created above and display it

#include<stdio.h>
void main(int argc,char *argv[])
{
char ch;
FILE *fp;
fp=fopen(argv[1],"w");
while((ch=getchar())!=EOF)
fputc(ch,fp);
fclose(fp);
fp=fopen(“xyz.c”,”r”);
while((ch=fgetc(fp))!=EOF)
printf(“%c”,ch);
fclose(fp);
}//main

K.Vigneswara Reddy, Dept. of I.T


Random access to files
• So far we have used functions to read or write data
sequentially.
• How do you access a file randomly?

• To access the particular part of the file use the


following functions
1. ftell() - current position of the file pointer in a file
2. fseek() – move to particular position in a file.
3. rewind() – moves file pointer to the beginning of the
file.

K.Vigneswara Reddy, Dept. of I.T


ftell() current position in a file
• ftell()-
• This function gives the current position of the file pointer in a
file, relative to beginning of a file.
• It measures the position in the file by the number of bytes,
relative to zero, from the beginning of the file.
• Returns the no of bytes from the beginning of a file to current
position.
• syntax long int ftell(File Pointer);

K.Vigneswara Reddy, Dept. of I.T


rewind()- rewind file
• rewind() – this function takes the file pointer to the
beginning of the file.
• Used when you want to read a file more than one time
without close and open a file.
• to change a work file from a write state to a read
state.
• syntax
void rewind(file pointer);

K.Vigneswara Reddy, Dept. of I.T


• rewind(fp);
rewind(fp);
n=ftell(fp);
here n=0
Remember that the first byte in the file
is numbered as 0.

K.Vigneswara Reddy, Dept. of I.T


fseek()- set particular position
• fseek()- sets the file pointer to a particular position in a file.
• We can move forward and backward within the file.
Syntax
int fseek(FILE *stream, long offset, int position);
Where
FILE *stream- file pointer
offset- specifies the number of positions to be moved from the
location specified by the position.
Position- it may have three values.
0- beginning of the file
1- current position
2- end of the file.
If offset is +ve it moves forward , -ve moves backward
When operation is successful it returns the value zero else returns
-1
K.Vigneswara Reddy, Dept. of I.T
Operations of fseek()
Statement Meaning
fseek(fp,0L,0); Go to the beginning.
fseek(fp,0L,1); Stay at the current position.
fseek(fp,0L,2); Go to the end of the file, past the last character
of the file.
fseek(fp,m,0) Move to (m+1)th byte in the file from
beginning
fseek(fp,m,1); Go forward by m bytes from current location
fseek(fp,-m,1); Go backward by m bytes from the current
position.
fseek(fp,-m,2); Go backward by m bytes from the end.
(positions the file to the character from the end.)
K.Vigneswara Reddy, Dept. of I.T
#include<stdio.h>
void main() Example illustrates ftell(),fseek() and rewind()
{
FILE *fptr;
char ch;
long int n=0L;
fptr=fopen("fseekExout.c","w+");
while((ch=getchar())!=EOF)
fputc(ch,fptr);
printf("\n");
printf("\ncurrent position of file pointer is %ld and character is
%c",ftell(fptr),getc(fptr));
rewind(fptr);
fseek(fptr,n,0);
printf("\ncharacter at this position is %c=",getc(fptr));
fseek(fptr,10L,1);
printf("\n charcter at position is %c=",getc(fptr));
fclose(fptr); K.Vigneswara Reddy, Dept. of I.T
}//main
C program to read name and marks of n number of students and
store them in a file.

for(i = 0; i < num; ++i)


#include <stdio.h> {
int main() { printf("For student%d\nEnter name: ", i+1);
char name[50]; scanf("%s", name);
int marks, i, num; printf("Enter marks: ");
scanf("%d", &marks);
printf("Enter number of students: ");
fprintf(fptr,"\nName: %s \nMarks=%d \n",
scanf("%d", &num); name, marks);
FILE *fptr; }
fptr = (fopen("C:\\student.txt", "w")); fclose(fptr);
if(fptr == NULL) return 0;
} Note: if we want to check the
{
file exist or not if its exist our
printf("Error!");
data need to be added to the
exit(1); exisiting file, to do this just we
} have to change the mode of file
from write (w) to append (a).
K.Vigneswara Reddy, Dept. of I.T
/** * C program to find file permission, size, creation and last modification date of
a given file. */

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>

void printFileProperties(struct stat stats);

int main()
{
char path[100];
struct stat stats;

printf("Enter source file path: ");


scanf("%s", path);

// stat() returns 0 on successful operation,


// otherwise returns -1 if unable to get file properties.
if (stat(path, &stats) == 0)
{
printFileProperties(stats);
K.Vigneswara Reddy, Dept. of I.T
}
else
{
printf("Unable to get file properties.\n");
printf("Please check whether '%s' file exists.\n", path);
}
return 0;
}

/** * Function to print file properties. */


void printFileProperties(struct stat stats)
{
struct tm dt;

// File permissions
printf("\nFile access: ");
if (stats.st_mode & R_OK)
printf("read ");
if (stats.st_mode & W_OK)
printf("write ");
if (stats.st_mode & X_OK)
printf("execute");

// File size
K.Vigneswara Reddy, Dept. of I.T
printf("\nFile size: %d", stats.st_size);
// Get file creation time in seconds and
// convert seconds to date and time format

dt = *(gmtime(&stats.st_ctime));

printf("\nCreated on: %d-%d-%d %d:%d:%d", dt.tm_mday, dt.tm_mon,


dt.tm_year + 1900,dt.tm_hour, dt.tm_min, dt.tm_sec);

// File modification time


dt = *(gmtime(&stats.st_mtime));

printf("\nModified on: %d-%d-%d %d:%d:%d", dt.tm_mday, dt.tm_mon,


dt.tm_year + 1900, dt.tm_hour, dt.tm_min, dt.tm_sec);

K.Vigneswara Reddy, Dept. of I.T


#include<stdio.h>
#include<sys/stat.h>
int checkIfFileExists(const char *filename);
int main(void) {
if(checkIfFileExists("demo.txt"))
{
printf("file exists");
}
else
{
printf("file does not exists");
}}
int checkIfFileExists(const char* filename){
struct stat buffer;
int exist = stat(filename,&buffer);
if(exist == 0) return 1; else return 0;
K.Vigneswara Reddy, Dept. of I.T
}

You might also like