The C Fopen Function Is Used to Open a File for FILE Level Access. X

The C Fopen Function Is Used to Open a File for FILE Level Access. X

File Structures

2.4.2 Files with C Streams and C++ Stream Classes xFor FILE level access, the logical file is declared as a pointer to a FILE (FILE *) x The FILE structure is defined in the stdio.h header file. Opening

The C++ fopen function is used to open a file for FILE level access. x

  • The FILE fopen function must be supplied with (as arguments):
  • The name of the physical file
  • The access mode
  • xThe value returned by the fopen is a pointer to an open FILE, and is assigned to the file variable.

fopen function:

Prototypes:

FILE * fopen (const char* Filename, char * Access);

Example:

FILE * Input;

Input = fopen ("Daily.txt", "r");

The access mode should be one of the following strings:

  • r Open for reading (existing file only) in text mode
  • r+ Open for update (existing file only)
  • w Open (or create) for writing (and delete any previous data)
  • w+ Open (or create) for update (and delete any previous data)
  • aOpen (or create) for append with file pointer at current EOF (and keep any previous data) in text mode a+
  • Open (or create) for append update (and keep any previous data)

Closing

  • The C++ fclose function is used to close a file for FILE level access.
  • The FILE fclose function must be supplied with (as an argument):
  • A pointer to the FILE structure of the logical file
  • The value returned by the fclose is 0 if the close succeeds, and &neq;0 if the close fails..
  • Prototypes:

intfclose (FILE * Stream);

Example:

fclose (Input);

Reading

The C++ fread function is used to read data from a file for FILE level access.

  • The FILE fread function must be supplied with (as an arguments):
  • A pointer to the FILE structure of the logical file
  • The address of the buffer into which the data will be read
  • The number of items to be read
  • The size of each item to be read, in bytes
  • The value returned by the fread function is the number of items read.

Prototypes:

size_tfread (void * Buffer, size_t Size, size_t Count, FILE * Stream); Example:

fread (&C, 1, 1, Input);

Writing

The C++ fwrite function is used to write data to a file for FILE level access.

  • The FILE fwrite function must be supplied with (as an arguments):
  • A pointer to the FILE structure of the logical file oThe address of the buffer from which the data will be written o The number of items to be written o The size of each item to be written, in bytes
  • The value returned by the fwrite function is the number of items written.
  • Prototypes: size_tfwrite (void * Buffer, size_t Size, size_t Count, FILE * Stream); Example:
  • fwrite (&C, 1, 1, Output);

Department of ISE NIT,Raichur