Saturday, July 14, 2012

Opening and Closing Streams in ANSI C

The ANSI C library stdio.h provides support for working with files and streams. To use a file, a pointer is necessary to make the connection between the physical file and the C I/O system.

1.Opening a stream
FILE* fopen(char* fileName, char* mode)
Description:
The function opens a stream to the named file (specified by its file name - char* fileName) in a specified mode (specified by char* mode).

The available modes are:
"rt"\"rb" Open file for reading
"wt"\"wb" Create file for writing. If any previous content exist, it shall be discarded
"at"\"ab" Opens or creates a file for writing, starting at the end of the file
"r+t"\"r+b" Open a file for update
"w+t"\"w+b" Creates text file for update. If any previous content exist, it shall be discarded
"a+t"\"a+b" Opens or creates a file for writing, starting at the end of the file

Files can be opened in text mode (example: "rt" opens a file for reading in text mode while "rb" opens a file for reading in binary mode).

The update mode (example "w+t") permits reading and writing on the same file. You must use int fflush(FILE* stream) or a file-positioning function between a read and a write to move the cursor at the position you want.
Returns:
The function returns a stream (FILE*) to the file if the call is successful. Otherwise returns NULL.
Tips&Tricks:
-The number of characters in a file name is limited by the FILENAME_MAX macro.
-The number of opened streams (files) is limited by the FOPEN_MAX macro.

2.Closing a Stream
int fclose(FILE* stream).
Description:
The function flushes any unwritten data for the stream sent as parameter, discards any unread buffered input and frees any automatically allocated buffer. After that it closes the stream.
Returns
0 - if the stream was successfully closed
EOF - if an error happened while closing the stream.

3.Example
#include<stdio.h>

int main(void)
{
   /*Variables*/
   FILE* f = NULL;
   int status = 0;

   /*Opens the stream*/
   f = fopen("file1.txt","rt");
   /*Checks if the stream was opened correctly*/
   if(NULL!=f)
   {
      puts("File was opened successfully");
      /*Closes the file*/
      status = fclose(f);
      /*Checks if the stream was closed correctly*/
      if(0==status)
      {
          puts("File closed successfully");
      }
      else
      {
          puts("File could not be closed");
      }
   }  
   else
   {
      puts("Could not access file");
   }
   return 0;
}


No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger