All file input and output is done with what kind of data

A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.

In C language, we use a structure pointer of file type to declare a file.

FILE *fp;

C provides a number of functions that helps to perform basic file operations. Following are the functions,

Functiondescription
fopen()create a new file or open a existing file
fclose()closes a file
getc()reads a character from a file
putc()writes a character to a file
fscanf()reads a set of data from a file
fprintf()writes a set of data to a file
getw()reads a integer from a file
putw()writes a integer to a file
fseek()set the position to desire point
ftell()gives current position in the file
rewind()set the position to the begining point

Opening a File or Creating a File

The fopen() function is used to create a new file or to open an existing file.

General Syntax:

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

Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.

filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types,

modedescription
ropens a text file in reading mode
wopens or create a text file in writing mode.
aopens a text file in append mode
r+opens a text file in both reading and writing mode
w+opens a text file in both reading and writing mode
a+opens a text file in both reading and writing mode
rbopens a binary file in reading mode
wbopens or create a binary file in writing mode
abopens a binary file in append mode
rb+opens a binary file in both reading and writing mode
wb+opens a binary file in both reading and writing mode
ab+opens a binary file in both reading and writing mode

Closing a File

The fclose() function is used to close an already opened file.

General Syntax :

int fclose( FILE *fp);

Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File

In the above table we have discussed about various file I/O functions to perform reading and writing on file. getc() and putc() are the simplest functions which can be used to read and write individual characters to a file.

#include<stdio.h> int main() { FILE *fp; char ch; fp = fopen("one.txt", "w"); printf("Enter data..."); while( (ch = getchar()) != EOF) { putc(ch, fp); } fclose(fp); fp = fopen("one.txt", "r"); while( (ch = getc(fp)! = EOF) printf("%c",ch); // closing the file pointer fclose(fp); return 0; }

Reading and Writing to File using fprintf() and fscanf()

#include<stdio.h> struct emp { char name[10]; int age; }; void main() { struct emp e; FILE *p,*q; p = fopen("one.txt", "a"); q = fopen("one.txt", "r"); printf("Enter Name and Age:"); scanf("%s %d", e.name, &e.age); fprintf(p,"%s %d", e.name, e.age); fclose(p); do { fscanf(q,"%s %d", e.name, e.age); printf("%s %d", e.name, e.age); } while(!feof(q)); }

In this program, we have created two FILE pointers and both are refering to the same file but in different modes.

fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be printed on the console using standard printf() function.

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write in a file. In both the modes, new file is created if it doesn't exists already.

The only difference they have is, when you open a file in the write mode, the file is reset, resulting in deletion of any data already present in the file. While in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the file.

Reading and Writing in a Binary File

A Binary file is similar to a text file, but it contains only large numerical data. The Opening modes are mentioned in the table for opening modes above.

fread() and fwrite() functions are used to read and write is a binary file.

fwrite(data-element-to-be-written, size_of_elements, number_of_elements, pointer-to-file);

fread() is also used in the same way, with the same arguments like fwrite() function. Below mentioned is a simple example of writing into a binary file

const char *mytext = "The quick brown fox jumps over the lazy dog"; FILE *bfp= fopen("test.txt", "wb"); if (bfp) { fwrite(mytext, sizeof(char), strlen(mytext), bfp); fclose(bfp); }

fseek(), ftell() and rewind() functions

  • fseek(): It is used to move the reading control to different positions using fseek function.
  • ftell(): It tells the byte location of current position of cursor in file pointer.
  • rewind(): It moves the control to beginning of the file.

Some File Handling Program Examples


A computer file is used to store data in digital format like plain text, image data, or any other content. Computer files can be organized inside different directories. Files are used to keep digital data, whereas directories are used to keep files.

Computer files can be considered as the digital counterpart of paper documents. While programming, you keep your source code in text files with different extensions, for example, C programming files end with the extension .c, Java programming files with .java, and Python files with .py.

File Input/Output

Usually, you create files using text editors such as notepad, MS Word, MS Excel or MS Powerpoint, etc. However, many times, we need to create files using computer programs as well. We can modify an existing file using a computer program.

File input means data that is written into a file and file output means data that is read from a file. Actually, input and output terms are more related to screen input and output. When we display a result on the screen, it is called output. Similarly, if we provide some input to our program from the command prompt, then it is called input.

For now, it is enough to remember that writing into a file is file input and reading something from a file is file output.

File Operation Modes

Before we start working with any file using a computer program, either we need to create a new file if it does not exist or open an already existing file. In either case, we can open a file in the following modes −

  • Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode.

  • Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode.

  • Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode.

  • Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode.

In the following sections, we will learn how to open a fresh new file, how to write into it, and later, how to read and append more content into the same file.

Opening Files

You can use the fopen() function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Here is the prototype, i.e., signature of this function call −

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

Here, filename is string literal, which you will use to name your file and access mode can have one of the following values −

Sr.No Mode & Description
1

r

Opens an existing text file for reading purpose.

2

w

Opens a text file for writing. If it does not exist, then a new file is created. Here, your program will start writing content from the beginning of the file.

3

a

Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here, your program will start appending content in the existing file content.

4

r+

Opens a text file for reading and writing both.

5

w+

Opens a text file for both reading and writing. It first truncates the file to zero length, if it exists; otherwise creates the file if it does not exist.

6

a+

Opens a text file for both reading and writing. It creates a file, if it does not exist. The reading will start from the beginning, but writing can only be appended.

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is −

int fclose( FILE *fp );

The fclose( ) function returns zero on success, or EOF, special character, if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.

There are various functions provided by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see a few of them in the next section.

Writing a File

Given below is the simplest function to write individual characters to a stream −

int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success, otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s into the file referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can also use the function int fprintf(FILE *fp,const char *format, ...) to write a string into a file. Try the following example −

#include <stdio.h> int main() { FILE *fp; fp = fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...\n"); fputs("This is testing for fputs...\n", fp); fclose(fp); }

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.

Reading a File

Given below is the simplest function to read a text file character by character −

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return value is the character read; or in case of any error, it returns EOF. The following function allows you to read a string from a stream −

char *fgets( char *buf, int n, FILE *fp );

The function fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.

If this function encounters a newline character '\n' or EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) to read strings from a file, but it stops reading after encountering the first space character.

#include <stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("/tmp/test.txt", "r"); fscanf(fp, "%s", buff); printf("1 : %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("2: %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("3: %s\n", buff ); fclose(fp); }

When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −

1 : This 2 : is testing for fprintf... 3 : This is testing for fputs...

Let's analyze what happened here. First, the fscanf() method reads This because after that, it encountered a space. The second call is for fgets(), which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.

File I/O in Java

Java provides even richer set of functions to handle File I/O. For more on this topic, we suggest you to check our Java Tutorials.

Here, we will see a simple Java program, which is equivalent to the C program explained above. This program will open a text file, write a few text lines into it, and close the file. Finally, the same file is opened and then read from an already created file. You can try to execute the following program to see the output −

import java.io.*; public class DemoJava { public static void main(String []args) throws IOException { File file = new File("/tmp/java.txt"); // Create a File file.createNewFile(); // Creates a FileWriter Object using file object FileWriter writer = new FileWriter(file); // Writes the content to the file writer.write("This is testing for Java write...\n"); writer.write("This is second line...\n"); // Flush the memory and close the file writer.flush(); writer.close(); // Creates a FileReader Object FileReader reader = new FileReader(file); char [] a = new char[100]; // Read file content in the array reader.read(a); System.out.println( a ); // Close the file reader.close(); } }

When the above program is executed, it produces the following result −

This is testing for Java write... This is second line...

File I/O in Python

The following program shows the same functionality to open a new file, write some content into it, and finally, read the same file −

# Create a new file fo = open("/tmp/python.txt", "w") # Writes the content to the file fo.write( "This is testing for Python write...\n"); fo.write( "This is second line...\n"); # Close the file fo.close() # Open existing file fo = open("/tmp/python.txt", "r") # Read file content in a variable str = fo.read(100); print str # Close opened file fo.close()

When the above code is executed, it produces the following result −

This is testing for Python write... This is second line...