Friday, July 29, 2016

C Basics - File Handling in C

C language allows creating, opening, editing, and closing text or binary file. A file represents a sequence of bytes, regardless of it being a text file or a binary file.

Creating/Opening/Closing a file:
The function fopen() is used to create a new file or open an existing file.

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

This function returns file pointer, an object of the type FILE.
filename – name of the file with its file extension. It accepts absolute or relative path.
mode – access mode can have one of the following values.
"r" – reading mode, "w"- writing mode, "a"- appending mode. For w and a, a new file is created if the file does not exist.

"r+"," w+", "a+" - Opens a text file for both reading and writing. If it does not exist, then a new file is created.

To handle binary files, use following access modes: "rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
The function fclose( ) is used to close a file.

int fclose( FILE *fp );

This function returns zero on success, or EOF if there is an error in closing the file.

Writing to file:
The function int fputc( int c, FILE *fp ) writes the character c to the file referenced by fp.
The function int fputs( const char *s, FILE *fp )writes the string s to the file referenced by fp.
The function int fprintf(FILE *fp,const char *format, ...)writes the formatted output to the file referenced by fp.

Reading from file:
The function int fgetc( FILE * fp ) reads a character from the file referenced by fp.
The function char *fgets( char *buf, int n, FILE *fp ) reads up to n-1 characters from the file referenced by fp.
The function int fscanf(FILE *fp,const char *format, ...)reads formatted input from the file referenced by fp.

#include <stdio.h>

int main( ) {
   
   FILE *fp;
   char buff[255];
 
   printf("Writing to file..\n");
   fp = fopen("test.txt", "w+");
   fprintf(fp, "Writing to file using fprintf...\n");
   fputs("Writing to file using fputs...\n", fp);
   fclose(fp);
   
   printf("Reading from file..\n");
   fp = fopen("test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("fscnaf : %s\n", buff );

   fgets(buff, 255, (FILE*)fp);
   printf("fgets: %s", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("fgets: %s", buff );
   fclose(fp);
   
   return 0;
}

Binary IO functions:
There are two functions, that can be used for binary input and output:
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Both of these functions should be used to read or write blocks of memories - usually arrays or structures.



Related topics:
Standard Input-Output in C   |   Preprocessors in C   |   Header Files in C   |   Type Casting in C   |   Error Handling in C

List of topics: C Programming

No comments:

Post a Comment