10. Files

Introduction to File handling

In programming, we may require some specific input data to be generated several numbers of times. Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is impossible to recover the programmatically generated data again and again. However, if we need to do so, we may store it onto the local file system which is volatile and can be accessed every time. Here, comes the need of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local file system through our C program. 

The following operations can be performed on a file.

  1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
  2. Opening an existing file (fopen)
  3. Reading from file (fscanf or fgets)
  4. Writing to a file (fprintf or fputs)
  5. Moving to a specific location in a file (fseek, rewind)
  6. Closing a file (fclose)

1). Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The syntax of the fopen() is given below.

Syntax:-

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

The fopen() function accepts two parameters:

  • The file name (string). If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".
  • The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.


Example:-
#include <stdio.h>
int main() {
FILE *fp;
fp  = fopen ("data.txt", "w");
}

2). Closing a File: fclose()

The fclose() function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.

Syntax:-

int fclose( FILE *fp );

3).Reading File : fscanf() 

The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file.

Syntax:

int fscanf(FILE *stream, const char *format [, argument, ...])  

Example:-
#include <stdio.h>  
main(){  
   FILE *fp;  
   char buff[25]; //creating char array to store data of file  
   fp = fopen("file abc.txt", "r");  
   while(fscanf(fp, "%s", buff)!=EOF){  
   printf("%s ", buff );  
   }  

   fclose(fp);  

}  

Output:

      Hello,scanf is use...

4). Writing File : fprintf() 

The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.

Syntax:

int fprintf(FILE *stream, const char *format [, argument, ...])  

Example:-
#include <stdio.h>  
main(){  
   FILE *fp;  
   fp = fopen("file.txt", "w");   //opening file  
   fprintf(fp, "Hello file by fprintf...\n");   //writing data into file  
   fclose(fp);//closing file  
}  

5). Writing a File: fputc()

The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error.
Syntax:-
   int fputc( int c, FILE *fp );
Example:-
#include <stdio.h>

int main()
 {
   FILE *fp;
   fp = fopen("/tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}

6). Reading a File:fgetc() 

The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF
Syntax:-
  int fgetc( FILE * fp );

The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
Example:-
#include <stdio.h>

int main() {

   FILE *fp;
   char buff[250];
   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1 : %s\n", buff );
   fgets(buff, 250, (FILE*)fp);
   printf("2: %s\n", buff );
   fgets(buff, 250, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);

}

Output:-

         1 : This
         2: is testing for fprintf...
         3: This is testing for fputs...


Enumeration

Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration.

Syntax:-
enum enum_name{const1, const2, ....... };

The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows.
 i). enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};
ii). enum week day;

Example:-
#include<stdio.h> enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; int main() { int i; for (i=Jan; i<=Dec; i++) printf("%d ", i); return 0; }
Output:- 0 1 2 3 4 5 6 7 8 9 10 11

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive.
There are two types of macros:

i). Object-like Macros
ii).Function-like Macros

i).Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants.

Example:-
#define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.
ii). Function-like Macros The function-like macro looks like function call.

Example:- #define MIN(a,b) ((a)<(b)?(a):(b))
Here, MIN is the macro name.

Preprocessor:-


The source code written by programmers is stored in the file program.c. This file is then processed by preprocessors and an expanded source code file is generated named program. This expanded file is compiled by the compiler and an object code file is generated named program .obj. Finally, the linker links this object code file to the object code of the library functions to generate the executable file program.exe.

Preprocessor programs provide preprocessors directives which tell the compiler to preprocess the source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that, whatever statement starts with #, is going to the preprocessor program, and preprocessor program will execute this statement.

 Example:-

 #include#define#ifndef etc.


Post a Comment

0 Comments