File Handling in C Language

                  File Handling in C Language

file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.

ModeDescription
rOpens an existing text file for reading purpose.
wOpens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file.
aOpens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content.
r+Opens a text file for reading and writing both.
w+Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist.
a+Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
The fclose() function is used to close an already opened file.Closing a File

General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.


Writing a File

Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
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. You can use the following functions to write a null-terminated string to a stream:
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.
Try the following example:
#include <stdio.h>

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);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in next section.

Reading a File

Following is the simplest function to read a single character from a file:
int fgetc( FILE * fp );
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.
char *fgets( char *buf, int n, 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.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after the first space character encounters..
#include <stdio.h>

main()
{
   FILE *fp;
   char buff[255];

   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1 : %s\n", buff );

   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);

}
When the above code is compiled and executed, it reads the file created in previous section and produces the following result:
1 : This
2: is testing for fprintf...

3: This is testing for fputs...
Let's see a little more detail about what happened here. First fscanf() method read just Thisbecause after that it encountered a space, second call is for fgets() which read the remaining line till it encountered end of line. Finally last call fgets() read second line completely.

Input/Output operation on File

#include<stdio.h>
#include<conio.h>
main()
{
 FILE *fp;
 char ch;
 fp = fopen("one.txt", "w");
 printf("Enter data");
 while( (ch = getchar()) != EOF) {
    putc(ch,fp);
 }
 fclose(fp);
 fp = fopen("one.txt", "r");
 while( (ch = getc()) != EOF)
    printf("%c",ch);
 fclose(fp);
}


Reading and Writing from File using fprintf() & fscanf()

#include<stdio.h>
#include<conio.h>
struct emp
{
   char name[10];
   int age;
};

void main()
{
   struct emp e;
   FILE *p,*q;
   p = fopen("one.txt", "a");
   q = fopen("one.txt", "r");
   printf("Enter Name and Age");
   scanf("%s %d", e.name, &e.age);
   fprintf(p,"%s %d", e.name, e.age);
   fclose(p);
   do
   {
      fscanf(q,"%s %d", e.name, e.age);
      printf("%s %d", e.name, e.age);
   }
   while( !feof(q) );
   getch();
}
In this program, we have create two FILE pointers and both are refering to the same file but in different modes.fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be printed on console usinf standard printf() function.

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in deletion of any data already present in the file. While in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the file.

fseek(), ftell() and rewind() functions

  • fseek() - It is used to move the reading control to different positions using fseek function.
  • ftell() - It tells the byte location of current position of cursor in file pointer.
  • rewind() - It moves the control to beginning of the file.









C – Operators and Expressions


  • The symbols which are used to perform logical and mathematical operations in a C program are called C operators.
  • These C operators join individual constants and variables to form expressions.
  • Operators, functions, constants and variables are combined together to form expressions.
  • Consider the expression A + B * 5. where, +, * are operators, A, B  are variables, 5 is constant and A + B * 5 is an expression.

Types of C operators:

C language offers many types of operators. They are,

    1. Arithmetic operators
    2. Relational operators
    3. Logical operators
    4. Bit wise operators
    5. Assignment operators
    6. Conditional operators (ternary operators)
    7. Increment/decrement operators
    8. Special operators

Arithmetic Operators

Following table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
+Adds two operandsA + B will give 30
-Subtracts second operand from the firstA - B will give -10
*Multiplies both operandsA * B will give 200
/Divides numerator by de-numeratorB / A will give 2
%Modulus Operator and remainder of after an integer divisionB % A will give 0
++Increments operator increases integer value by oneA++ will give 11
--Decrements operator decreases integer value by oneA-- will give 9

Arithmetic operator are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus

Relational Operators

These operators are basically used to compare the value of two variables.
Following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20, then:
OperatorDescriptionExample
==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

Logical Operators

These operators are basically used to perform logical operations on the given two variables.
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then:
OperatorDescriptionExample
&&Called Logical AND operator. If both the operands are non-zero, then condition becomes true.(A && B) is false.
||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.(A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:
pqp & qp | qp ^ q
00000
01011
11110
10011
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:
OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12, which is 0000 1100
|Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61, which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49, which is 0011 0001
~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) will give -61, which is 1100 0011 in 2's complement form.
<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

Assignment Operators

Assignment Operators are used to assign the values for the variables in C programs.
There are following assignment operators supported by C language:
OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
<<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

 sizeof & ternary(conditional operators)

There are few other important operators including sizeof and ? : supported by C Language.
Conditional operators return one value if condition is true and returns another value is condition is false.
show example
OperatorDescriptionExample
sizeof()Returns the size of an variable.sizeof(a), where a is integer, will return 4.
&Returns the address of an variable.&a; will give actual address of the variable.
*Pointer to a variable.*a; will pointer to a variable.
? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y

Increment/decrement operators

These operators are used to either increase or decrease the value of the variable by one

Special operators

    • Below are some of special operators that C language offers.
 S.no
Operators
Description
1
&
This is used to get the address of the variable.
Example : &a will give address of a.
2
*
This is used as pointer to a variable.
Example : * a  where, * is pointer to the variable a.
3
Sizeof ()
This gives the size of the variable.
Example : size of (char) will give us 1.

Example program for & and * operators in C:

    • In this program, “&” symbol is used to get the address of the variable and “*” symbol is used to get the value of the variable that the pointer is pointing to. Please refer C – pointer topic to know more about pointers.

Output:

50
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity 
Postfix () [] -> . ++ - -  Left to right 
Unary + - ! ~ ++ - - (type)* & sizeof Right to left 
Multiplicative  * / % Left to right 
Additive  + - Left to right 
Shift  << >> Left to right 
Relational  < <= > >= Left to right 
Equality  == != Left to right 
Bitwise AND Left to right 
Bitwise XOR Left to right 
Bitwise OR Left to right 
Logical AND && Left to right 
Logical OR || Left to right 
Conditional ?: Right to left 
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left 
Comma Left to right