File Handling in ‘C’
Contents
• Need for file
• Streams in ‘C’
• Bufffers Associated
• Types
• Operations
• Working with files
• File modes
What is a File?
• A file is a collection of related data that a computers treats
as a single unit.
• Computers store files to secondary storage so that the
contents of files remain intact when a computer shuts
down.
• When a computer reads a file, it copies the file from the
storage device to memory; when it writes to a file, it
transfers data from memory to the storage device.
• C uses a structure called FILE (defined in stdio.h) to store
the attributes of a file.
Stored file on disk
Steams in’C‘
• Streams are termed as preconnected input and output
channels between text terminal and program(where
began execution)
• Streams are logical interface to a file,where it can refer to
a file, computer scree, keyboard..
• A Stream is a linked to a file using open operation
• Disassociated from a file with close operation
Types of Streams
• stdin -standard input
• stdout standard output keyboard
• stderr -standard error stdin
program
stdout stderr
screen
diagram :flow of data in streams
stdin -standard input
• stdin is the stream which the programs receive its data
• the program requests transfer of data using read
operations
• not all programs require input
• unless redirected , all inputs from keyboard
stdout -standard output
• stdout is the stream where a program writes its output
data
• the program requests data transfer using the write
operation
• not all programs generate ouput
stderr -standard err
• stderr is a output stream used by a porgram to report
error messages.
• independent of standard ouput , that can be redirected
seperately
• stderr & stdout can be directed to the same destination
Buffers Associated
• when a file is created , A Buffer is created auomatically
and associated with stream
• Block of memory for temporary storage of data the has
read from or to write a file
• Buffers are hardware independent
• Acts as a interface between stream(characer oriented)
and disk(block oriented)
Buffer associated with streams
Program Data from
writes data Buffer is
to Buffer written to
PROGRAM disk
BUFFER DISK
diagram :flow of data in Buffer
Types of Files
• When dealing with files, there are two types of files you
should know about:
• Text files
• Binary files
Text files
• Text files are the normal .txt files. You can easily create
text files using any simple text editors such as Notepad.
• When you open those files, you'll see all the contents
within the file as plain text. You can easily edit or delete
the contents.
• They take minimum effort to maintain, are easily readable,
and provide the least security and takes bigger storage
space.
Binary files
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the
binary form (0's and 1's).
• They can hold a higher amount of data, are not readable
easily, and provides better security than text files.
File Operations
• In C, you can perform four major operations on files,
either text or binary:
• Creating a new file
• Opening an existing file
• Closing a file
• Reading from and writing information to a file
Working with files
• When working with files, you need to declare a pointer of
type file. This declaration is needed for communication
between the file and the program.
• FILE *fptr;
Steps in Processing a File
• Create the stream via a pointer variable using the FILE
structure: FILE *p;
• Open the file, associating the stream name with the file
name.
• Read or write the data.
• Close the file.
The basic file functions are
– fopen - open a file- specify how its opened
(read/write) and type (binary/text)
– fclose - close an opened file
– fread - read from a file
– fwrite - write to a file
– fseek/fsetpos - move a file pointer to
somewhere in a file.
– ftell/fgetpos - tell you where the file pointer is
located.
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”);
More On fopen 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:
• spData = fopen(“[Link]”, “w”);
• spData = fopen(“A:\\[Link]”, “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(spData);
• fprintf() Syntax: fprintf (fp,"string",variables); Example:
• int i = 12;
• float x = 2.356;
• char ch = 's';
• FILE *fp;
• fp=fopen(“[Link]”,”w”);
• fprintf (fp, "%d %f %c", i, x, ch);
• fscanf() Syntax: fscanf (fp,"string",identifiers);
Example: FILE *fp;
• Fp=fopen(“[Link]”,”r”);
• int i;
• fscanf (fp,“%d",i);
getc()
• Syntax: identifier = getc (file pointer); Example:
FILE *fp;
• fp=fopen(“[Link]”,”r”);
• char ch;
• ch = getc (fp);
• putc() write a single character to the output file,
pointed to by fp.
• Example:
• FILE *fp;
• char ch;
• putc (ch,fp);
End of File
• There are a number of ways to test for the end-of-file
condition. Another way is to use the value returned by
the fscanf function:
• FILE *fptr1;
• int istatus ;
• istatus = fscanf (fptr1, "%d", &var) ;
• if ( istatus == feof(fptr1) )
• {
• printf ("End-of-file encountered.\n”) ;
• }
Reading and Writing Files
– #include <stdio.h>
– int main ( )
–{
– FILE *outfile, *infile ; int b = 5, f ;
– float a = 13.72, c = 6.68, e, g ;
– outfile = fopen ("testdata", "w") ;
– fprintf (outfile, “ %f %d %f ", a, b, c) fclose (outfile) ;
– infile = fopen ("testdata", "r") ;
– fscanf (infile,"%f %d %f", &e, &f, &g) ;
– printf (“ %f %d %f \n ", a, b, c) ;
– printf (“ %f %d %f \n ", e, f, g) ;
Example
• #include <stdio.h> #include<conio.h> void main() {
• char ch;
• FILE *fp;
• fp=fopen("[Link]","r");
• while(!feof(fp))
• ch=getc(fp);
• printf("\n%c",ch);
• }
• getch();
read data from files
• fscanf()
• fgets()
• fgetc()
• fread()
writing data to a file
• fprintf()
• fputs()
• fputc()
• fwrite()
detecting EOF
• character by chacter
• feof(fp)
• fread ()
• Declaration:
• size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
• Remarks:
• fread reads a specified number of equal-sized
• data items from an input stream into a block.
• ptr = Points to a block into which data is read
• size = Length of each item read, in bytes
• n = Number of items read
• stream = file pointer
• Example Example: #include <stdio.h> int main() { FILE *f;
• char buffer[11];
• if (f = fopen("[Link]", “r”))
• fread(buffer, 1, 10, f);
• buffer[10] = 0;
• fclose(f);
• printf("first 10 characters of the file:\n%s\n", buffer);
• }
• return 0;
• }
• fwrite() Declaration:
• size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
• Remarks:
• fwrite appends a specified number of equal-sized data items to
an output file.
• ptr = Pointer to any object; the data written begins at ptr
• size = Length of each item of data
• n =Number of data items to be appended
• stream = file pointer
• Example Example: #include <stdio.h> int main() { }
• char a[10]={'1','2','3','4','5','6','7','8','9','a'};
• FILE *fs;
• fs=fopen("[Link]","w");
• fwrite(a,1,10,fs);
• fclose(fs);
• return 0;
• }
• fseek()
• This function sets the file position indicator for the stream pointed to by
stream or you can say it seeks a specified place within a file and modify it.
• SEEK_SET Seeks from beginning of file
• SEEK_CUR Seeks from current position
• SEEK_END Seeks from end of file
• Example:
• #include <stdio.h>
• int main()
• { FILE * f; f = fopen("[Link]", "w"); fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END fputs(" India", f);
fclose(f); return 0; }
• ftell() offset = ftell( file pointer );
• "ftell" returns the current position for input or output on the file
• #include <stdio.h>
• int main(void)
• {
• FILE *stream;
• stream = fopen("[Link]", "w");
• fprintf(stream, "This is a test");
• printf("The file pointer is at byte %ld\n", ftell(stream));
• fclose(stream);
• return 0;
• }