Learn how to Make Money Online | Free Tech Magazines
Go4Expert
Go4Expert RSS Feed

Go Back   Programming and SEO Forum >  Go4Expert > Articles / Source Code > Programming > C-C++

Discuss / Comment Copy HTML to Clipboard  Copy BBCode to Clipboard  Add to del.icio.us  Add to Google  Digg it  Add to Yahoo !  Add to Windows Live  Add to Facebook  Add to StumbleUpon 
 
Bookmarks Article Tools Search this Article Display Modes

File read write in plain C

By Sanskruti Sanskruti is offline

On 13th February, 2007
Cool File read write in plain C

ADVERTISEMENT
Show Printable Version Email this Page Subscription Add to Favorites Copy File read write in plain C link

Author

Sanskruti ( Ambitious contributor )

Yet to provide details about himself


All articles By Sanskruti

Recent Articles

Similar Articles

Opening A File

Before we can write information to a file on a disk or read it, we must open the file. Opening a file establishes a link between the program and the operating system, about, which file we are going to access and how. We provide the operating system with the name of the file and whether we plan to read or write to it. The link between our program and the operating system is a structure called FILE which has been defined in the header file “stdio.h” . Therefore, it is necessary to always include this file when we are doing high level disk I/O. When we request the operating system to a file, what we get back is a pointer to the structure FILE. That is why, we make the following declaration before opening the file,

FILE*fp ;

Each file we open will have its own FILE structure. The FILE structure contains information about the file being used, such as its current size, its location in memory etc. More importantly it contains a character pointer which points to the character that is about to get read.

Now let us understand the following statements,

FILE *fp ;
fp = fopen ( “PR1.C”, “r” ) ;

fp is a pointer variable, which contains address of the structure FILE which has been in the header file “stdio.h”.

fopen( ) will open a file “PR1.C” in ‘read’ mode, which tells the compiler that we would be reading the contents of the file. Note that “r” is a string and not a character; hence the double quotes and not single quotes.

In fact, fopen( ) performs three important tasks when you open the file in “r” mode:

(a) Firstly it searches on the disk the file to be opened.
(b) If the file is present, it loads the file from the disk into memory. Of course if the file is very big, then it loads the file part by part.If the file is absent, fopen( ) returns a NULL.NULL is a macro defined in “stdio.h” which indicates that you failed to open the file.
(c) It sets up a character pointer which points to the first character of the chunk of memory where the file has been loaded.

Reading from A file

Once the file has been opened for reading using fopen( ), the file’s contents are brought into memory and a pointer points to the very first character. To read the file’s contents from memory there exists a function called fgetc( ). This has been used in our sample program through,

ch = fgetc ( fp ) ;

fgetc( ) reads the character from current pointer position, advances the pointer position so that it now points to the next character, and returns the character that is read, which we collected in the variable ch. Note that once the file has been opened, we refer to the file through the file pointer fp.

We have to use the function fgetc( ) within an indefinite while loop. There has to be a way to break out of this while,it is the moment we reach the end of file. End of file is signified by a special character in the file, when it is created. This character can also be generated from the keyboard by typing ctrl Z.

While reading from the file, when fgetc( ) encounters this special character, instead of returning the character that it has read, it returns the macro EOF. The EOF macro has been defined I the file “stdio.h”. In place of the function fgetc( ) we could have as well used the macro getc( ) with the same effect.

Opening A File

There is a possibility that when we try to open a file using the function fopen( ), the file may not be opened. While opening the file in “r” mode, this may happen because the file being opened may not be present on the disk at all. And you obviously cannot read a file which doesn’t exist. Similarly, while opening the file for writing, fopen( ) may fail due to a number of reasons, like, disk space may be insufficient to open a new file, or the disk may be write protected and so on.

So it is important for any program that accesses disk files to check whether a file has been opened successfully before trying to read or write to the file. If the file opening fails due to any of the several reasons mentioned above, the fopen( ) function returns a value NULL (defined in “stdio.h” as #define NULL 0).

Here is how this can be handled in a program…

Code: C
#include “stdio.h
main()
{
         FILE*fp ;

         Fp = fopen ( “PR1.C”,”r” ) ;
         if( fp == NULL )
         {
               puts ( “cannot open file” ) ;
               exit() ;
         }
}
File Opening Modes

We open the file in read ( “r” ) mode. However, “r” is but one of the several modes in which we can open a file. Following is a list of all possible modes in which a file can be opened . the tasks performed by fopen( ) when a file is opened in each of these modes are also mentioned.

r :- Searches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn’t exit it returns NULL.

Operations possible – reading from the file.

w :- Searches file. If the file exists, its contents are overwritten. If the file doesn’t exit, a new file is created. Returns NULL, if unable to open file.

Operations possible – writing to the file.

a :- Searches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.

Operations possible – appending new contents at the end of file.

r+ :- Searches file. If it exists, loads it into memory and sets up a pointer which points to the first character in it. If file doesn’t exist it returns NULL.

Operations possible – reading existing contents, writing new contents, modifying existing contents of the file.

w+ :- Searches file. If the file exists, its contents are destroyed. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file.

Operations possible – writing new contents, reading them back and modifying existing contents of the file.

a+ :-Searches file. If the file exists, loads it in to memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.

Operations possible – reading existing contents, appending new contents to end of file. Cannot modify existing contents.

Writing to A File

The fputc( ) function is similar to the putch( ) function, in the sense that both output characters. However, putch( ) function always writes to the VDU, whereas, fputc( ) writes to the file. Which file? The file signified by ft. the writing process continues till all characters from the source file have been written to the target file, following which the while loop terminates.

We have already seenthe function fgetc( ) which reads characters from a file. Its

Counterpart is a function called fputc( ) which writes characters to a file. As a practical use of these character I/O functions we can copy the contents of one file into another, as demonstrated in the following example. This program takes the contents of a text file and copies them into another text file, character by character.

Example

Code: C
#include “stdio.h
main()
{
        FILE *fs, *ft ;
        char ch ;

        fs = fopen ( “pr1.c”, “r” ) ;
        if ( fs == NULL )
        {
               puts ( “Cannot open source file” ) ;
               exit( ) ;
        }

        ft = fopen ( “pr2.c”, “w” ) ;
        if ( ft == NULL )
        {
               puts ( “Cannot open target file” ) ;
               fclose ( fs ) ;
               exit( ) ;
        }

        while ( 1 )
        {
               ch = fgetc ( fs ) ;

               if ( ch == EOF )
                      break ;
               else
                   
                       fputc ( ch, ft )  ;
        }

        fclose ( fs ) ;
        fclose (t
}
Closing The File

When we have finished reading from the file, we need to close it. This is done using the function fclose( ) through the statement,

fclose ( fp ) ;

this deactivates the file and hence it can no longer be accessed using getc( ). Once again we don’t use the filename but the file pointer fp.
Old 04-12-2007, 11:07 AM   #2
Peter_APIIT
Contributor
 
Join Date: Apr 2007
Location: Malaysia
Posts: 92
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 3
Peter_APIIT is on a distinguished road
Send a message via MSN to Peter_APIIT

Re: File read write in plain C


I don't understand what this statemnet does fputc ( ch, ft ) .

Your explanation and teaching is greatly appreciated by me and others.

Thanks for your help.
__________________
C and C++ is the best languages in the world.
Peter_APIIT is offline   Reply With Quote
Old 04-12-2007, 11:42 AM   #3
shabbir
Go4Expert Founder
 
shabbir's Avatar
 
Join Date: Jul 2004
Location: On Earth
Posts: 10,943
Thanks: 35
Thanked 167 Times in 139 Posts
Rep Power: 10
shabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud of
Send a message via Yahoo to shabbir

Re: File read write in plain C


fputc ( ch, ft ) puts the character ch into the file ft opened by fopen
shabbir is offline   Reply With Quote
Old 04-12-2007, 07:02 PM   #4
Peter_APIIT
Contributor
 
Join Date: Apr 2007
Location: Malaysia
Posts: 92
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 3
Peter_APIIT is on a distinguished road
Send a message via MSN to Peter_APIIT

Re: File read write in plain C


Is it possible to copy directly from a file to another file in c without go through the ch ?

Thanks for your help.


Hope this can help others also.
__________________
C and C++ is the best languages in the world.
Peter_APIIT is offline   Reply With Quote
Old 04-12-2007, 07:04 PM   #5
shabbir
Go4Expert Founder
 
shabbir's Avatar
 
Join Date: Jul 2004
Location: On Earth
Posts: 10,943
Thanks: 35
Thanked 167 Times in 139 Posts
Rep Power: 10
shabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud of
Send a message via Yahoo to shabbir

Re: File read write in plain C


Nope or probably I have no idea relating to the same and you can always try that.
shabbir is offline   Reply With Quote
Old 04-12-2007, 07:05 PM   #6
Peter_APIIT
Contributor
 
Join Date: Apr 2007
Location: Malaysia
Posts: 92
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 3
Peter_APIIT is on a distinguished road
Send a message via MSN to Peter_APIIT

Re: File read write in plain C


OK. Thanks for your patient and explanations.
__________________
C and C++ is the best languages in the world.
Peter_APIIT is offline   Reply With Quote
Discuss / Comment Copy HTML to Clipboard  Copy BBCode to Clipboard  Add to del.icio.us  Add to Google  Digg it  Add to Yahoo !  Add to Windows Live  Add to Facebook  Add to StumbleUpon 


Currently Active Users Reading This Article: 1 (0 members and 1 guests)
 
Article Tools Search this Article
Search this Article:

Advanced Search
Display Modes
Bookmarks

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads / Articles
Thread Thread Starter Forum Replies Last Post
100 Multiple choice questions in C coderzone C-C++ 98 08-26-2009 12:17 AM
File Handling in C - File Pointers pradeep C-C++ 2 05-23-2008 02:30 PM
File Splitter and Merger Jaihind C-C++ 2 03-06-2008 01:34 PM
File Splitter and Merger Jaihind C-C++ 0 08-26-2006 01:42 PM

 

All times are GMT +5.5. The time now is 04:41 AM.