Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

File Handling in C Programming: A Comprehensive Guide, Study notes of Programming Languages

A comprehensive guide to file handling in c programming. It covers essential concepts such as file opening modes, file positioning functions, and the differences between text and binary files. The document also includes practical examples illustrating how to read and write data to files, copy files, and count characters, digits, spaces, and words in a text file. It further explores command line arguments and binary file functions, offering a solid foundation for understanding and implementing file handling techniques in c.

Typology: Study notes

2023/2024

Available from 01/07/2025

tanisha-17
tanisha-17 🇮🇳

1 document

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
UNIT-III
File Handling
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.
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 file
Creating a Stream
We can create a stream when we declare it. The declaration uses the FILE type as shown below,
The FILE type is a structure that contains the information needed for reading and writing a file,
fp is a pointer to the stream.
Opening File
Once stream has been created, we can ready to associate to a file. In the next section we will
discuss in detail.
Closing the Stream
When file processing is complete, we close the file. After closing the file the stream is no longer
available.
File Open and Close
In this section we discuss the C functions to open and close streams.
File Open (fopen)
To open a file, we need to specify the physical filename and its mode.
Syntax,
FILE *fp;
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download File Handling in C Programming: A Comprehensive Guide and more Study notes Programming Languages in PDF only on Docsity!

UNIT-III

File Handling

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. 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 file Creating a Stream We can create a stream when we declare it. The declaration uses the FILE type as shown below,

The FILE type is a structure that contains the information needed for reading and writing a file, fp is a pointer to the stream. Opening File Once stream has been created, we can ready to associate to a file. In the next section we will discuss in detail. Closing the Stream When file processing is complete, we close the file. After closing the file the stream is no longer available.

File Open and Close In this section we discuss the C functions to open and close streams. File Open (fopen) To open a file, we need to specify the physical filename and its mode. Syntax,

*FILE fp;

fopen (“filename”, “mode”); The file mode is a string that tells C compiler how we intend to use the file: read existing file, write a new file or append to a file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure. The actual contents of the FILE are hidden from our view. All we need to know is that we can store the address of the file structure and use it to read or write the file. The statement: fptr1 = fopen (“mydata", "r”); Would open the file mydata for input (reading). The statement: fptr2 = fopen ("results", "w”); Would open the file results for output (writing). Once the files are open, they stay open until you close them or end the program (which will close all files.)

File Modes:- (IMPORTANT) When we open a file, we explicitly define its mode. The mode shows how we will use the file: for reading, for writing, or for appending. “r” (read) mode The read mode (r) opens an existing file for reading. When a file is opened in this mode, the file marker is positioned at the beginning of the file (first character). The file marker is a logical element in the file structure that keeps track of our current position in the file. The file must already exist: if it does not, NULL is returned as an error. If we try to write a file opened in read mode, we get an error message. Syntax fp=fopen (“filename”,”r”); “w” (write) mode The write mode (w) opens for writing. If the file doesn’t exist, it is created. IF it is already exists, it is opened and all its data are erased; the file marker is positioned at the beginning of the file (first character) It is an error to try to read from a file opened in write mode. Syntax fp=fopen (“filename”,”w”); “a” (append) mode The append mode (a) also opens an existing for writing. Instead of creating a new file, however, the writing starts after the last character; that is new data is added, or appended, 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 fp=fopen (“filename”,”a”); “r+” (read and write) mode In this mode file is opened for both reading and writing the data. If a file does not exist then NULL, is returned. Syntax: fp=fopen (“filename”,”r+”); “w+” (read and write) mode In this mode file is opened for both writing and reading the data. If a file already exists its contents erased. If a file does not exist then new file created. Syntax: fp=fopen (“filename”,”w+”); “a+” (append and read) mode In this mode file is opened for reading the data as well as data can be added at the end. Syntax: fp=fopen (“filename”, “a+”);

(IMPORTANT)

File and Terminal Input Function

File and Terminal Output Function

Formatted Input Function

fscanf ():  The general format of fscanf() is, fscanf (stream_pointer,”format string”, list);

 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 following example illustrates how to read data from keyboard using fscanf, fscanf (stdin,”%d”, &a);

Formatted Output Function

fprintf ()  The general form of fprintf is fprintf (stream_pointer, ”format string”, list);  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) ;

 Example, fprintf (stdout,”%d”,45); displays 45 on Monitor.

UnFormatted Input Function

TERMINAL AND FILE

CHARACTER I/O

Read a Character: getc () and fgetc () Syntax for using getc/fgetc, getc (fp); fgetc (fp);

Example, char ch; ch = getc (stdin); /* input from keyboard */

UnFormatted Output Function

Write a Character: putc () and fputc ()

Syntax, **putc (char, fp); fputc (char, fp);

Example, char ch; ch = getc (stdin); /* input from keyboard / putc (ch, stdout); / output to the screen */

ch =fgetc (fileptr); /* input from a file */

putc (ch, outfileptr); /*output to a file */ UnFormatted Input Function

LINE I/O FUNCTIONS

Reading Strings: fgets ()  The general format, fgets (string, length, fp);  fgets also reads data from terminal. Below example illustrates this, fgets (str, 10, stdin);

UnFormatted Input Function

Writing Strings: fputs ()  The general format forms are fputs (string, fp);

TEXT FILES AND BINARY FILES

Differences between Text File and Binary File (IMPORTANT)

The differences between text file and binary file are as shown in Table. The

following Figure illustrates the storage difference between text file and

binary file.

Figure 6.11 Binary and Text Files

FILE POSITIONING FUNCTIONS IMPORTANT

File positioning functions have two uses. First, for randomly processing data in disk files, we need to position the file to read the desired data. Second, we can use the positioning functions to change a file’s state. Thus, we can change the state of the file pointer using one of the positioning functions. There three file position functions,  tell location  rewind file  file seek Current Location: ftell ()  The ftell function reports the current position of the file marker in the file, relative to the beginning of the file.  ftell () takes a file pointer and returns a number of type long integer, that corresponds to the current position.  Here the return type is long integer because many files have more than 32,767 bytes. The operation ftell is graphically shown in Figure 6.14.  The syntax of ftell function as follows, n= ftell(fp);  n would give the relative offset of the current position. This means that n bytes have already been read (or written).  If ftell encounters an error, it returns -1.  Let us consider the following statement, n=ftell (fp);

Figure 6.14 Working of ftell Function  The above Figure 6.14 illustrates the working of ftell, it returns 16, and the current offset value.  The primary purpose of ftell is to provide a data address (offset) that can be used in a file seek. It is especially helpful when we are dealing with text file for which we cannot calculate the position of data. Rewind File: rewind ()  The rewind function simply sets the file position indicator to the beginning of the file as shown in Figure 6.15.  This function helps us in reading a file more than once, without having to close and open the file.

 Its common use is to change a work from a write state to a read state. However, that to read and write a file with only one open, we must open it in update mode w+.  Syntax to use rewind function is as follows, rewind (fp);  Example: rewind (fp); n=ftell (fp); Would assign 0 to n because the file position has been set to the start of the file by rewind.

Figure 6.15 Working of ftell Function

Set Position: fseek ()  fseek () function is used to move the file position to a desired location within the file.  It takes the following form: fseek (file_ptr, offset, position);  file_ptr is a pointer to the file concerned, offset is a number or variable of type long, and position is an integer number.  The offset specifies the number of positions to be moved from the location specified by position.  The position can take one of the following three values: Value Meaning 0 beginning of file. 1 Current position. 2 End of file.  The offset may be positive, meaning move forwards, or negative, meaning move backwards.  The following Table 6.3 illustrate operations of the fseek() function:

ch=fgetc(fp); //Reading a character from file. putchar(ch); //Writing character to the screen. }

fclose(fp);

getch(); }

Example2: WAP to transfer the contents of a file into another file. (i.e. copy one file to another file. IMPORTANT #include<stdio.h> #include<conio.h>

void main() { FILE *fp1, *fp2; char ch='a';

clrscr();

fp1=fopen("INPUT.txt","w");

printf("Enter text to be stored in file Input.txt\n"); while(ch!='\n') { ch=getchar(); //Reading a character from keyboard and stores in variable ch fputc(ch,fp1); //Writing character to the file. } fclose(fp1);

fp1=fopen("INPUT.txt","r");

printf("\n Contents of INPUT.txt\n"); while(ch!=EOF) { ch=fgetc(fp1); //Reading from INPUT.txt putchar(ch); //Writing to the screen } fclose(fp1);

fp1=fopen("INPUT.txt","r"); fp2=fopen("OUTPUT.txt","w");

ch=' '; //Refreshing character variable

// Copying contents of INPUT.txt into OUTPUT.txt while(ch!=EOF) { ch=fgetc(fp1); //Reading from INPUT.txt putc(ch,fp2); //Writing to OUTPUT.txt } fclose(fp1); fclose(fp2);

fp2=fopen("OUTPUT.txt","r"); ch=' ';

printf("\n Contents of OUTPUT.txt\n"); while(ch!=EOF) { ch=fgetc(fp2); //Reading from OUTPUT.txt putchar(ch); //Writing to the screen }

fclose(fp2);

getch(); }

Example 3: WAP to count the number of characters, digits, spaces and words in a text file.IMPORTANT

#include<stdio.h> #include<conio.h>

void main() { FILE *fp; char ch='a'; int ch_count=0,dg=0,sp=0;

clrscr();

fp=fopen("INPUT.txt","w");

printf("Enter text to be stored in file Input.txt\n"); while(ch!='\n') { ch=getchar(); //Reading a character from keyboard and stores in variable ch fputc(ch,fp); //Writing character to the file.

Command line arguments It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code. The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly − #include <stdio.h>

int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } }

Example: WAP to copy one file to another using command line arguments.IMPORTANT #include<stdio.h> #include<conio.h>

void main(int argc, char *argv[]) { FILE *fp1, *fp2; char ch=' ';

clrscr();

if(argc<3) { printf("Number of arguments are not valid."); exit(0); }

fp1=fopen(argv[1],"r"); fp2=fopen(argv[2],"w");

// Copying contents of INPUT.txt into OUTPUT.txt while(!feof(fp1)) { ch=fgetc(fp1); //Reading from INPUT.txt putc(ch,fp2); //Writing to OUTPUT.txt } fclose(fp1); fclose(fp2);

getch(); }

Binary Files Functions OPTIONAL

fread – read from

binary file

int fread( void *buffer, size_t size, size_t num, FILE *ptr )

buffer – stores the value read size – size of the buffer num – number of blocks to be read ptr – file pointer Returns – number of values read

Char *str = malloc(50);

fread(str,50,1,infile);

fwrite – write to a

binary file

int fwrite( void *buffer, size_t size, size_t num, FILE *ptr )

buffer – stores the value read size – size of the buffer num – number of blocks to be read ptr – file pointer Returns – number of values written

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

fwrite(&i,sizeof(i),1,outfile);

char a[]=”end”;

fwrite(a,strlen(a)+1,1,outfile);

/ Program to Write to a binary file using fwrite() /

#include <stdio.h> #include <stdlib.h>

struct threeNum { int n1, n2, n3; };