Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

file input output operations

The document provides an overview of file I/O operations in C programming, detailing the concepts of streams, file access methods, and file operations. It distinguishes between text and binary streams, explains the significance of newline and EOF markers, and outlines various file opening modes and operations such as reading and writing files. Additionally, it includes example code snippets demonstrating how to read from and write to files using C functions.

Uploaded by

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

file input output operations

The document provides an overview of file I/O operations in C programming, detailing the concepts of streams, file access methods, and file operations. It distinguishes between text and binary streams, explains the significance of newline and EOF markers, and outlines various file opening modes and operations such as reading and writing files. Additionally, it includes example code snippets demonstrating how to read from and write to files using C functions.

Uploaded by

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

BS(INFORMATION TECHNOLOGY).

Programming Fundamentals

Programming Fundamentals
BS(IT) 1st semester

File I/O operations

Stream
A logical interface to a file is known as stream. It is a flow of data. A sequence a characters
from an input device to computer is called input stream. A sequence of character from computer
to output device is called output stream. A stream is associated with a fil using an open operation.
The stream is disassociated from a file using a close operation.
Types of Streams
There are two types of streams in C language:
1. Text Stream
A text stream is a sequence of characters, A certain character translation may occur in text
stream. For example, a new line may be converted to a carriage return/line feed pair, means that
there may not be a one-to-one relationship between the written characters and the characters in
external device.
2. Binary Stream
A binary stream is a sequence of bytes. The translation is not performed in binar stream. It
exists with a one-to-one correspondence to the external devices. It means that th number of bytes
written or read is the same as the number of bytes on the external device However, an
implementation-defined number of bytes may be appended to a binary stream
BS(INFORMATION TECHNOLOGY). Programming Fundamentals

Difference between Text and Binary Stream

Text Stream Binary streams


It is a sequence of It is a sequence of bytes.
characters.

It does not have a one- It has a one-to-one relationship


to-one relationship with external devices.
with external devices
A certain character No translation occurs in binary
translation may occur stream.
in text stream.
It is less efficient than It is more efficient than text
binary stream. stream.

It can be used only for It can be used for different types


text data. of data.

File access methods


The way in which a file can be accessed is called file access method. It depends on manner in
which data is stored in the files.
Different file access methods are as follows
❖ Sequential Access Method
❖ Random Access Method

1. Sequential Access Method


Sequential access method is used to access data in the same sequence in which
stored in file. This method reads and writes data in a sequence In order to read the last
record, it has to read all records stored before the last one. It is simple but slow and time
method may take a lot of time.

2. Random access method


Random access method is used to access any data item directly without accessing the
preceding data. This method does not read or write data in sequence. It is very last access
method as compared to sequential access method. A searching operation with random
access method takes far less time to find a data item.
BS(INFORMATION TECHNOLOGY). Programming Fundamentals

What is use of Newline and EOF markers in files?


EOF
A text file is a named collection of characters saved in secondary storage such as disk.
The text file has no fixed size. The end-of-file is a special character. It is used to indicate the end
of a text file. It is placed after the last character in the file.
It is added automatically at the end of files. A constant EOF represents end of file character.
while((ch = fgetc(in)) != EOF)
printf("%c",ch);

The above loop will continues to execute until it finds the EOF character

New Line

The ENTER key is used to move the cursor to the next line in a text editors such as Notepad. A
newline character is placed at the end of each line when the user presses Enter key. The newline
is denoted by \n in C.

Data file
A data file is a collection of related records. A record contains data about an entity. Data file can
be used to save any type of data. Files are stored on secondary storage. The data is stored in files
permanently.

Normally, a program inputs data from user and stores it in variables. The data stored in the
variables is temporary. When the program ends, all data stored in variables is also destroyed. The
user has to input data again from keyboard when the program is executed next time. The data has
to be entered each time program is executed that wastes time. The user may also type wrong data
at different times.

Use of Data Files


BS(INFORMATION TECHNOLOGY). Programming Fundamentals

A data file can be used to provide input to a program. output of a program permanently. If a
program gets input from a file instead of keyboard, it will get the same data each time it is executed.
There will be far less chance of errors. can also be used to store the

Text Files
A type of file that stores data as readable and printable characters is called text file. A source
program of C language is an example of text file. The user can easily view and read the contents
of a text file. It can also be printed to get a hard copy.
Pointer
A type of variable that is used to store the memory address of a memory cell is known as pointer.
It normally stores the memory address of a variable or object. The data type of a pointer must be
same as data type of the variable whose memory address is stored in pointer.

File Pointer
File pointer is pointer that refers to file on the secondary storage. It is variable of FILE that is
defined in stdio.h. It used to access and manipulate data file. program to declare file pointer to use
file. The file pointer is associated with file after declaration. One file pointer can be associated
with only one data file.
syntax
The syntax for declaring file pointer as follows:
FILE "MyFile;

The identifier MyFile is file pointer. FILE the type of MyFile pointer. The symbol indicates that it
is pointer to file structure. This structure defined in stdio.h header file. contains all information
that required to manage files. must be included in the program to manipulate files.

File Operations

There are different operations that can be carried out on a file.


▸ Creation of a new file
▸ Opening an existing file
▸ Reading from a file
BS(INFORMATION TECHNOLOGY). Programming Fundamentals

▸ Writing to a file

Opening a file
A file should be opened before can processed. All standard file handling functions C declared in
stdio.h. must be included almost every program. file pointer declared and associated with the file
to opened. function fopen used open file.
Syntax
The syntax of fopen function is follows:
File Pointer= fopen(File Name, Mode):

Various File Opening Modes:


The file is opened using fopen() function, while opening you can use any of the following mode
as per the requirement.
Mode “r”: It is a read only mode, which means if the file is opened in r mode, it won’t allow you
to write and modify content of it. When fopen() opens a file successfully then it returns the address
of first character of the file, otherwise it returns NULL.

Mode “w”: It is a write only mode. The fopen() function creates a new file when the specified file
doesn’t exist and if it fails to open file then it returns NULL.

Mode “a”: Using this mode Content can be appended at the end of an existing file. Like Mode
“w”, fopen() creates a new file if it file doesn’t exist. On unsuccessful open it returns NULL.File
Pointer points to: last character of the file.

Mode “r+”: This mode is same as mode “r”; however you can perform various operations on the
file opened in this mode. You are allowed to read, write and modify the content of file opened in
“r+” mode.
File Pointer points to: First character of the file.

Mode “w+”: Same as mode “w” apart from operations, which can be performed; the file can be
read, write and modified in this mode.
Mode “a+”: Same as mode “a”; you can read and append the data in the file, however content
modification is not allowed in this mode.
BS(INFORMATION TECHNOLOGY). Programming Fundamentals

Reading a File
To read the file, we must open it first using any of the mode, for example if you only want to read
the file then open it in “r” mode. Based on the mode selected during file opening, we are allowed
to perform certain operations on the file.

C Program to read a file


fgetc( ): This function reads the character from current pointer’s position and upon successful read
moves the pointer to next character in the file. Once the pointers reaches to the end of the file, this
function returns EOF (End of File). We have used EOF in our program to determine the end of
the file.

#include <stdio.h>
int main()
{
/* Pointer to the file */
FILE *fp1;
/* Character variable to read the content of file */
char c;

/* Opening a file in r mode*/


fp1= fopen ("C:\\myfiles\\newfile.txt", "r");

/* Infinite loop –I have used break to come out of the loop*/


while(1)
{
c = fgetc(fp1);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(fp1);
return 0;
}

Writing to a file
To write the file, we must open the file in a mode that supports writing. For example, if you open
a file in “r” mode, you won’t be able to write the file as “r” is read only mode that only allows
reading.
BS(INFORMATION TECHNOLOGY). Programming Fundamentals

Example: C Program to write the file


This program asks the user to enter a character and writes that character at the end of the file. If
the file doesn’t exist then this program will create a file with the specified name and writes the
input character into the file.

#include <stdio.h>
int main()
{
char ch;
FILE *fpw;
fpw = fopen("C:\\newfile.txt","w");

if(fpw == NULL)
{
printf("Error");
exit(1);
}

printf("Enter any character: ");


scanf("%c",&ch);

/* You can also use fputc(ch, fpw);*/


fprintf(fpw,"%c",ch);
fclose(fpw);

return 0;
}

Closing a file
fclose(fp);
The fclose( ) function is used for closing an opened file. As an argument you must provide a
pointer to the file that you want to close.

An example to show Open, read, write and close operation in C


#include <stdio.h>
int main()
{
char ch;

/* Pointer for both the file*/


BS(INFORMATION TECHNOLOGY). Programming Fundamentals

FILE *fpr, *fpw;


/* Opening file FILE1.C in “r” mode for reading */
fpr = fopen("C:\\file1.txt", "r");

/* Ensure FILE1.C opened successfully*/


if (fpr == NULL)
{
puts("Input file cannot be opened");
}

/* Opening file FILE2.C in “w” mode for writing*/


fpw= fopen("C:\\file2.txt", "w");

/* Ensure FILE2.C opened successfully*/


if (fpw == NULL)
{
puts("Output file cannot be opened");
}

/*Read & Write Logic*/


while(1)
{
ch = fgetc(fpr);
if (ch==EOF)
break;
else
fputc(ch, fpw);
}

/* Closing both the files */


fclose(fpr);
fclose(fpw);

return 0;
}

How to read/ write (I/O) Strings in Files – fgets & fputs


Here we will discuss how to read and write strings into a file.

char *fgets(char *s, int rec_len, FILE *fpr)


s: Array of characters to store strings.
rec_len: Length of the input record.
fpr: Pointer to the input file.
Lets take an example:
BS(INFORMATION TECHNOLOGY). Programming Fundamentals

Example to read the strings from a file in C programming


#include <stdio.h>
int main()
{
FILE *fpr;
/*Char array to store string */
char str[100];
/*Opening the file in "r" mode*/
fpr = fopen("C:\\mynewtextfile.txt", "r");

/*Error handling for file open*/


if (fpr == NULL)
{
puts("Issue in opening the input file");
}

/*Loop for reading the file till end*/


while(1)
{
if(fgets(str, 10, fpr) ==NULL)
break;
else
printf("%s", str);
}
/*Closing the input file after reading*/
fclose(fpr);
return 0;
}
In the above example we have used fgets function like this:

fgets(str, 10, fpr)


Here str represents the string (array of char) in which you are storing the string after reading it
from file.
10 is the length of the string that needs to be read every time.
fpr is pointer to file, which is going to be read.

Why I used if(fgets(str, 10, fpr)==NULL as a logic to determine end of the file?
In the above examples, we have used ch==EOF to get to know the end of the file. Here we have
used this logic because fgets returns NULL when there is no more records are available to be read.

C Program – Writing string to a file


int fputs ( const char * s, FILE * fpw );
char *s – Array of char.
FILE *fpw – Pointer (of FILE type) to the file, which is going to be written.
BS(INFORMATION TECHNOLOGY). Programming Fundamentals

#include <stdio.h>
int main()
{
FILE *fpw;

/*Char array to store strings */


char str[100];

/*Opening the file FILEW.TXT in "w" mode for writing*/


fpw = fopen("C:\\mynewtextfile2.txt", "w");

/*Error handling for output file*/


if (fpw== NULL)
{
puts("Issue in opening the Output file");
}

printf("Enter your string:");

/*Stored the input string into array – str*/


gets(str);

/* Copied the content of str into file –


* mynewtextfile2.txt using pointer – fpw
*/
fputs(str, fpw);

/*Closing the Output file after successful writing*/


fclose(fpw);
return 0;
}
fputs takes two arguments –

fputs(str, fpw)
str – str represents the array, in which string is stored.
fpw – FILE pointer to the output file, in which record needs to be written.

Point to note about fputs:


fputs by default doesn’t add new line after writing each record, in order to do that manually – you
can have the following statement after each write to the file.

fputs("\n", fpw);

You might also like