0% found this document useful (0 votes)
79 views

B.C.A. Semester - II CA-118 Advanced Programming Unit-3 Files What Is A File?

The document discusses file handling in C programming. It defines a file, explains why files are needed, describes common file operations like opening, reading, writing and closing files. It also discusses functions for random access of files like fseek(), ftell() and rewind(). Functions to read and write characters, integers and strings from files like getc(), putc(), getw(), putw(), fscanf() and fprintf() are also covered.

Uploaded by

harsh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

B.C.A. Semester - II CA-118 Advanced Programming Unit-3 Files What Is A File?

The document discusses file handling in C programming. It defines a file, explains why files are needed, describes common file operations like opening, reading, writing and closing files. It also discusses functions for random access of files like fseek(), ftell() and rewind(). Functions to read and write characters, integers and strings from files like getc(), putc(), getw(), putw(), fscanf() and fprintf() are also covered.

Uploaded by

harsh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

B.C.A.

Semester - II

CA-118 Advanced Programming

Unit-3 Files

What is a File?

File is a collection of bytes that is stored on secondary storage devices like disk.

When a computer reads a file, it copies the file from the storage device to main memory.

When a computer writes to a file, it transfers data from main memory to the storage device.

C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.

Why File is needed?

When the program is terminated, the entire data is lost in C programming.

If you want to keep large volume of data, it is time consuming to enter the entire data.

But, if file is created, this information can be accessed using few commands.

Types of Files

1
File Operations

1. Creating a File

2. Opening an Existing File

3. Reading from a File or Writing Information to a File

4. Closing a Fie

2
Working with a File

To use files in C we must follow the steps given below:

1. Declare a file pointer variable

2. Open the file

3. Process the file

4. Close the file

While working with file, you need to declare a pointer of type FILE. This declaration is needed for
communication between file and program.

FILE *file_pointer_name;

Opening a File

A file must be opened before any operation can be performed on it.

Opening a file is performed using library function fopen().

The syntax for opening a file in standard I/O is:

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

For example,

FILE *fp;

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

Where,

fp – file pointer to the data type “FILE”.

a.txt – the actual file name with full path of the file.

w – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+ and a+.

Example: fopen("E:\\cprogram\\program.txt","w");

Here, the program.txt file is opened for writing mode.

3
File Modes:

Closing a File

The file should be closed after reading/writing of a file.

Closing a file is performed using library function fclose().

Syntax: fclose(fp); Here, fp is the file pointer associated with file to be closed.

fcloseall() close all files currently open for reading or writing mode.
4
fprintf()

The function fprintf() is the file version of printf(). The first argument is a pointer to the structure FILE.

Syntax:

FILE *fp;

fp = fopen(“a.txt”,”w”);

fprintf(FILE *stream, const char *format)

Example: fprintf(fp,” %d %d”,n1,n2);

#include<stdio.h>

void main()

FILE *fp;

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

fprintf(fp,"Hello File");

fclose(fp);

Ouput:

Hello File (It will be printed in a text file)

fscanf()

The function fscanf() is the file version of scanf().

The first argument is a pointer to the structure FILE.

Syntax:

FILE *fp;

fp = fopen(“a.txt”,”r”);

fscanf(FILE *stream, const char *format)

Example: fscanf(fp,” %d %d”,&n1,&n2);

5
#include <stdio.h>
void main()
{
FILE *fptr; // creating a FILE variable
int id, score;
int i, s;
char name[50];
char n[50];

// open the file in write mode


fptr = fopen("student", "w");

printf("Enter student name: ");


gets(name);
printf("Enter student ID: ");
scanf("%d", &id);
printf("Enter student score: ");
scanf("%d", &score);

// write data in file


fprintf(fptr, "%s %d %d", name, id, score);
fclose(fptr); // close connection

// open the file in a reading mode


fptr = fopen("student", "r");

// read data from a file


fscanf(fptr, "%s %d %d", n, &i, &s);

// display detail
printf("\nStudent Details:\n");
printf("\n Name: %s", n);
printf("\n ID: %d", i);
printf("\n Score: %d", s);

printf("\n\nEnd of file.\n");

fclose(fptr); // close connection


}
getc()

getc() is a file handling function in C programming language which is used to read a character from a
file.

The getc() will return an end-of-file marker EOF, when end of the file has been reached.

Therefore, the reading should be terminated when EOF is encountered.

getc(fp) would read a character from the file whose file pointer is fp.
6
putc()

putc() is a file handling function in C programming language which is used to display on standard output
or write into a file.

putc(c, fp) writes the character contained in the character variable c to the file associated with FILE
pointer fp.

NOTE: Ctrl + Z is used to stop input in a file.

#include<stdio.h>
void main()
{
FILE *f1;
char c;
printf("Data Input:\n\n");

/* Open the file INPUT */


f1 = fopen("INPUT.doc", "w");

/* Get a character from keyboard */


while((c=getchar())!= EOF)
{
putc(c,f1); /* Write a character to INPUT.doc file */
}
fclose(f1); /*Close the file INPUT.doc */

printf("\nData Output:\n\n");

/* Reopen the file INPUT.doc */


f1 = fopen("INPUT.doc","r");

/* Read a character from INPUT.doc file*/


while((c=getc(f1)) != EOF)
{
printf("%c",c); /* Display a character on screen*/
}
fclose(f1);
}
getw()

getw() is a file handling function in C programming language which is used to read an integer value
from a file.

The getw() will be useful when we deal with only integer data.
7
getw(fp) would read an integer value from the file whose file pointer is fp.

putw()

putw() is a file handling function in C programming language which is used to write an integer value in
a file.

The putw() will be useful when we deal with only integer data.

putw(i, fp) would write an integer value stored in a variable i in a file using file pointer is fp.

#include<stdio.h>
void main()
{
FILE *f;
int n1,n2,no1,no2,sum=0;

f=fopen("sat1.doc","w");
printf("Enter First Number = ");
scanf("%d",&n1);
printf("Enter Second Number = ");
scanf("%d",&n2);
putw(n1,f);
putw(n2,f);
fclose(f);

f=fopen("sat1.doc","r");
no1=getw(f);
no2=getw(f);
sum=no1+no2;
printf("\n The First Number = %d",no1);
printf("\n The Second Number = %d",no2);
printf("\n Summation = %d",sum);
fclose(f);
}

8
Random Access to Files

So far we have seen file functions that are useful for read and write data sequentially. However,
sometime we require to access only a particular part of a file. This can be achieved using fseek() , ftell()
and rewind() functions available in I/O library.

ftell()

ftell() gives current position of the file pointer in a file.

Ex. n = ftell(fp);

n would give the relative offset (in bytes) of the current position.

This means that n bytes are already there in a file.

fseek()

fseek() is used to move the file position to a desired location within the file.

Syntax: fseek(file_ptr, offset, position);

file_ptr is a pointer to the file concerned.

offset is a number or variable of type long

position is an integer number

The offset specifies the number of positions (bytes) 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

When the operation is successful, fseek returns a zero.

If we attempt to move the file pointer beyond the file boundaries, an error occurs and fseek returns -1
(minus one).

9
rewind()

rewind() takes a file pointer and resets the position to the start of the file.

rewind(fp);

n = ftell(fp);

Above two line code would assign 0 to n because the file position has been set to the start of the file by
rewind.

Remember, the first byte in the file is numbered as 0, second as 1, and so on.

Remember, that whenever a file is opened for reading or writing, a rewind is done implicitly.

rename()

The C library function rename() causes the filename referred to by old_filename to be changed
to new_filename.

Following is the declaration for rename() function.

rename(const char *old_filename, const char *new_filename);

For renaming a file successfully, it has to be closed, an open file cannot be renamed.

remove()

The C library function remove() deletes the given filename so that it is no longer accessible.

Following is the declaration for remove() function.

remove(const char *filename);

10

You might also like