Learn File Handling in easy way using C and Java

Learn File Handling in an easy way

Data files
Two types: one is input data file and another is output data file. If you want to permanently store your input data file to use it later.
Firstly, create input data file in some secondary storage device then the input data and save this input file permanently (in place of simply taking data temporarily from keyboard). Doing this our input data will be permanently stored and we can simply use this file anytime.
Similarly, we can save our outputs in Output data file permanently in place of simply displaying outputs only on the screen of a computer.

Various Function we will use in C for file handling

FILE *inp, *outp; // Makes cells named inp and outp for storage of file pointers.
inp=fopen( “num.dat”, “r”);//It opens num.dat as an input file, storing file pointer in inp. If this file is not opened properly then it returns NULL value.

outp= fopen( “num.out”, “w”); // It opens num.out as an output file and stores file pointer in outp. If this file is not opened properly then it returns NULL value.

fscanf(inp, “%d %d”, &mid, &low); // It copies input data from file num.dat into the type int variable mid and low.

fprintf(outp, “%d %d %d”, high,mid,low) ; // It stores in the file num.out a line containing the values of high , mid, and low.

fclose(inp); // Closes created input file num.dat

fclose(outp); // Closes newly created output file num.out

Various Function we will use in Java for file handling

BufferedReader in = new BufferedReader(new FileReader(“inputfile.txt”));

PrintWriter out = new PrintWriter(new FileWriter(“result.txt”)); //for writing
or
PrintWriter out = new PrintWriter(new FileWriter(“result.txt”, true));
//for appending

File handling in C


Open file

The system must prepare the file for input or output before permitting access i.e., the file should be opened for reading or writing by using the fopen function and a pointer to the file should be assigned to a FILE pointer variable. Consider the following

FILE *inpfile, *outfile ;
inpfile = fopen (“input.dat”, “r”) ;
outfile = fopen (“output.dat”, “w”) ;

In the above example, two pointers inpfile, outfile are declared as pointers to FILE. Next, the input.dat file is opened for reading (“r” indicates reading) and the FILE pointer inpfile is pointing to that input file input.dat. Next, the output.dat file is opened for writing (“w” indicates writing) and the FILE pointer outfile is pointing to that output file output.dat.
Now, the file can be accessed anywhere in the program by using the corresponding FILE pointers.
If you want to add to the end of the file use the mode “a” as o

utfile = fopen (“output.dat”, “a”) ;

Similarly, use the modes “r+” for read/write, “w+” for read/write as

outfile = fopen (“output.dat”, “r+”) ;


Not found

If the fopen function is unable to open the file, the file pointer that it returns will have a NULL value. The following statement detects for an unsuccessful attempt to open a file

if (inpfile == NULL)
printf (“Cannot open the file\n”) ;


Close a file

When a program has no further use for a file, it should close the file by using the function fclose with the file pointer pointing to the file to be closed as

fclose (inpfile) ;

The feof function (end of file):
In order to test for an end of file condition on a file when a file is being read, the function feof is provided. The single argument to the function is a FILE pointer. The function returns an integer value that is non-zero if all of the data from the specified file has been read, and is zero otherwise. So, the statement

if ( feof (inpfile) )
printf (“Ran out of data\n”) ;

will display the message if the end of file is reached when feof returns a zero. As seen above the feof takes the FILE pointer inpfile as its argument

The fscanf and fprintf functions:

The fprintf and fscanf functions are provided to perform the analogous operations of the printf and scanf functions on a file. The fscanf reads from a file and fprintf write to a file, whereas the scanf and printf read and write from/to the screen. The functions fprintf and fscanf take an additional argument, which is the FILE pointer that identifies the file to which that data is to be written or from which the data is to be read.
So, to write the line “I like C Programming” to the file pointed by outfile,
we write

fprintf (outfile, “I like C Programming\n”) ;

As seen above, the fprintf takes the pointer to FILE outfile as its first argument and the string to be written as its second argument.
To read the next float value from a file pointed by inpfile, we write

fscanf (inpfile, “%f”, &x) ;

As seen above, the fscanf function takes the pointer to FILE inpfile as its first argument, the format string as its second argument and the variable as its third argument. So, it is reading a float value from a file pointed by inpfile and assigning it to the variable x.
The fscanf function returns EOF (end of file) value if the end of file is reached. So, to read from the file pointed by inpfile and check whether it has reached an end of the file we write

if ( fscanf (inpfile, “%f”, &x) == NULL )
printf (“End of file\n”) ;

The fgets and fputs function:
For reading and writing entire lines of data from and to a file, the fgets and fputs functions can be used. The fgets function is called as follows:

fgets (buffer, n, file_pointer) ;

the buffer is a pointer to a character array where the line that is read will be stored; n is an integer value that represents the maximum number of characters that are to be stored in the buffer, and file_pointer identifies the file from which the line is to be read. The fgets function reads characters from the specified file until a newline character has been read or until n-1 characters have been read, whichever occurs first. The function automatically places a
null character after the last character in the buffer and returns the value of the buffer if the read is successful and the value NULL if an error occurs on the read or an attempt is made to read past the end of the file. The fputs function writes a line of characters to a specified file.

fputs (buffer, file_pointer) ;

Characters stored in the array pointed to by buffer are written to the file identified by file_pointer until the null character is reached. The terminating null character is not written out to the file.
The getc and putc functions:
The function getc enables us to read in a single character from a file and the putc function enables us to write a single character to a file. Both these functions take the FILE pointer as one of their arguments. The getc function returns the value EOF when the end of file is reached.

char c ;
c = getc (inpfile) ;
putc (‘a’, outfile) ;

The above getc reads a single character from the file pointed by inpfile and assigns it to the character variable c, the putc function writes the single character a to the file pointed to by outfile FILE pointer.
Note: Before you read from a file make sure that the file is opened in the reading mode and before you write to a file make sure that it is opened in the write mode.

File handling in Java

Reading Input from a file:
To read input from a file, we make use of the following classes from the java.io package:
FileReader: This is used to create an object that can be used to read one character from a file.
BufferedReader: This can be used together with a FileReader object to read one line from a text file.

BufferedReader in = new BufferedReader(new FileReader(“inputfile.txt”));

As we all know, the BufferedReader object has a readLine() that returns a string. When used to read a file, the readLine( ) method returns a whole line. It returns null if there is no more data in the file.
Notes:
• If the file does not exist, a FileNotFoundException is thrown.
• If the file is not in the current folder, the full path of the file must be specified.
• When specifying the full path of the file, it is better to use a forward slash.
Example: “C:/workarea/inputfile.txt”
• The backslash can also be used, but double slash must be used for each slash.
Example: “C:\\workarea\\inputfile.txt”

Writing/Appending output to text files:
To write or append output to a file, we make use of the following classes from the java.io package:
FileWriter: This is used to create an object that can be used to write one character to a file.
PrintWriter: To be able to write/append strings, we create a PrintWriter object, passing a FileWriter object as
a parameter:

PrintWriter out = new PrintWriter(new FileWriter(“result.txt”)); //for writing
or
PrintWriter out = new PrintWriter(new FileWriter(“result.txt”, true));
//for appending

The PrintWriter object has print() and println() methods that behave in exactly the same manner as those of
System.out object.
Notes:
• Unlike the case of FileReader object, if the file does not exist, it is created automatically. However, if there is no writing access to the file or its folder, a FileNotFoundException is thrown.

Some questions for you
Learn File Handling in easy way
Learn File Handling in easy way

For More question in File handling

 

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.