Loading, please wait...

File Processing

Streams and Files:

In C I/O system supplies a consistent interface to the programmer independent of the actual device being accessed. The I/O system provides a level of abstraction between the programmer and the device. This abstraction is called a stream, and the actual device is called a file.

 

There can be many peripheral devices connected to a computer, eg. Keyboard, screen, printer, mass storage device etc.

 

To perform I/O in a device-independent form, C treats each of them in the same way (as a file). A file can be thought of as a data set that can be read and written repeatedly

 

 

Stream:

A stream can be thought of as a buffer to which bytes flow from a device during an input operation and During an output operation bytes from the stream are made available to the device A stream can, therefore, be thought of as a high-level concept representing a communication channel to a data file or a device.

 

 

Text and Binary Stream

A text stream is an ordered sequence of characters composed into lines, terminated by a newline character Carriage return and line feed character combinations present in the file are translated into a new line character before being placed in the stream. Thus text streams are interpreted Binary streams are un-interpreted. They consist of one or more bytes of arbitrary information with no translation of the characters Thus what the program sees is exactly the same as what is actually present in the file.

 

 

Input/Output using streams:

To perform an operation on a file, the file must be opened first

The file is opened using the function fopen Opening a file with the function fopen creates a new stream and establishes a connection between the file and the stream.

 

 

The file pointer

FILE *fp;

A file pointer is a pointer to a structure of type FILE. It points to information that defines various things about the file, including its name, status, current position of the file

 

 

Opening a file:  fopen

The fopen() function opens a file for reading or writing for use and links a file with that stream Then it returns the file pointer associated with that file.

The fopen() function has the following  prototype:

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

the filename  is a pointer to a string of characters that make up a valid        filename and may include a path specification Mode determines how the    file will be opened. (r+b, rb+) fopen function  returns a file pointer. Your program should never alter the value of this pointer. If an error occurs when it is trying to open the file, fopen() returns a null pointer

 

The following Example uses fopen() to open a file .named test for output

FILE *fp;

if((fp = fopen(“test”,”w”))==NULL){

printf(“Cannot open file\n”);

exit(1);

}

  

          

Closing a file: fclose

The fclose function closes a stream that was opened by a call to fopen. It writes any data still remaining in the disk buffer to the file and does a formal operating system level close on the file.

 

Prototype of fclose

int fclose(FILE *fp);


fp is the file pointer returned by the call to fopen()

A return value of zero signifies a successful close operation

 

 

Function putc and getc

The putc() function writes characters to a file that was previously opened for writing using fopen() function The getc() function reads characters from a file opened in reading mode by fopen() .

 

Example: 

/*A C program to show use file input/output functions */

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[]){
FILE *fp;
char ch;
if(argc!=2){
printf(“You forgot to enter the filename\n”);
exit(1);
}
if((fp=fopen(argv[1], “w”)) == NULL){
printf(“Cannot open file\n”);
exit(1);
}
do{
ch = getchar();
putc(ch, fp);
} while(ch!= ‘$’);
fclose(fp);
return 0;

 

 

Function feof()

 Function feof() determines when the end of file has been encountered

Function feof() returns true if the end of the file has been reached, else it returns zero. It can be used for both binary and text files.

 

Prototype

int feof(FILE *fp);

 

Example:

If (feof(fptr)) puts(“End of input file reached”);

 

 

Function rewind()

It resets the file position indicator to the beginning of the file specified as its argument.The file can be an input or an output file.There is no need to declare this function before using it.

 

Prototype:

void rewind(FILE *fp);

Where fp is a valid file pointer

 

 

Function ferror() and clearer

It determines is a file operation error has occurred and to clear the error if it has.

Prototype:

 int ferror(FILE *fp);

Where fp is a valid file pointer It returns true if an error has occurred during the last file operation, otherwise, it returns false. Since each file operation sets the error condition ferror () should be called immediately after each file operation.

 

 

Function fremove()

fremove() function erases the specified file

Prototype:

int remove(const char *filename);

    

 

Function fflush()

fflush() flushes the contents of the output stream

Prototype: 

int fflush(FILE *fp);

This function writes the contents of any buffered data to the file associated with fp. If fflush() is called with fp being NULL, all files opened for output are flushes. fflush() function returns zero if successful otherwise  it returns EOF

 

 

Function fread() and fwrite()

These functions allow the reading and writing of blocks of any type of data Prototype:

size_t fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);

size_t fwrite(const void *buffer, size_t num_bytes, size_t count, FILE *fp);

size_t fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);

size_t fwrite(const void *buffer, size_t num_bytes, size_t count, FILE *fp);

For fread() buffer is a pointer to a region of memory that will receive the data from the file For fwrite() buffer is a pointer to the information that will be written to the file count determines the number of items read or written , each item being num_bytes in length fp is the file pointer to a previously opened stream. The fread() function returns the number of items read. 

 

This value may be less than count if the end of file is reached or an error occurs The fwrite() function returns the number of items written

This value equals count unless an error occurs.

 

 

Function fseek()

Random read and write operations can be performed using the function fseek() (it sets the file position indicator)

Prototype:

int fseek(FILE *fp, long int numbytes, int origin);

fp is the valid file pointer numbytes is the number of bytes from origin, which will become the current new position

Parameters or Arguments fp or stream is the stream whose file position indicator is to be modified.  numbytes or offset is the offset to use (in bytes) when determining the new file position. origin or whence can be one of the following values: SEEK_SET, SEEK_CUR, SEEK_END

 

 

Function fprintf() and fcsanf()

They are similar to printf() and scanf() functions, except that they operate on files

Prototype

int fprintf(FILE *fp, const char *control_string, …);

int fscanf(FILE *fp, const char *control_string, …);

 

 

Function rename()

The rename() function changes the name of the file specified by oldfname  to new fname The newfname must not match any existing directory entry, rename () function returns zero if successful and nonzero if an error has occurred.

 

Example:

#include<stdio.h>
int main(int argc, char *argv[ ])
{
if(rename(argv[1],argv[2])!= 0)
printf("Rename Error");
return 0;
}

 

 

Here, The table included Mode of File Processing and their brief description

 

Mode

Description

r

Open an existing file for reading.

w

Create a file for writing. If the file already exists, discard the current contents.

a

Append; open or create a file for writing at the end of the file.

r+

Open an existing file for update (reading and writing).

w+

Create a file for update. If the file already exists, discard the current contents.

a+

Append: open or create a file for update; writing is done at the end of the file.

rb

Open an existing file for reading in binary mode.

wb

Create a file for writing in binary mode. If the file already exists, discard the

current contents.

ab

Append; open or create a file for writing at the end of the file in binary mode.

rb+

Open an existing file for update (reading and writing) in binary mode.

wb+

Create a file for an update in binary mode. If the file already exists, discard the

current contents.

ab+

Append: open or create a file for an update in binary mode; writing is done at the

end of the file.