File to create, write, read and append in c

File handling in c:
  • So far, to write programs are done on command prompt or terminal (i.e. ubuntu os of cmd) which is not stored anywhere and most of the time we want to rewrite those programs.
  • But now a day we are using GUI level so we can easily store data in files, write also can be open and read.
  • If needs to store and fetched data in the file on your system, different operations are required to store by using ‘C’ language.
*Creation of a new file (fopen )
*Opening an existing file (fopen).
*Reading from file (fscanf or fgets).
*Writing to a file (fprintf or fputs).
*Moving to a specific location in a file (fseek, rewind).
*Closing a file (fclose).
  • C provides the number of functions that help to perform basic file operations.
  • File functions are,


  • Also, need modes for writing or read a file:


How to Create a File:
  • fopen is the standard function that is used to open a file.
  • If the file is not present on the system, then it is created and then opened.
  • If a file is already present on the system, then it is directly opened using this function.
Syntax:

 FILE *fp;
fp = fopen ("file_name", "mode");
where, fp is a pointer variable.

Example:

#include <stdio.h>
#include<conio.h>
int main() {
                      FILE *fp;
                      clrscr();
                      fp  = fopen ("welcome.txt", "w");//create new file
                      printf("\n File welcome.txt has been created");
                      getch();
                      return 0;
} 

Output:

 How to close the file:
  • The close file is used to close the opened file.
Syntax:

 fclose (file_pointer);

Example:

FILE *fp;
fp  = fopen ("file1.txt", "r");
fclose (fp);

How to writing to a File:
  • The write mode is used to write a given content into the file.
  • fputc(char, file_pointer): It writes a character to the file pointed to by file pointer.
  • fputs(str, file_pointer): It writes a string to the file pointed to by file pointer.
  • fprintf(file_pointer, str, variable_lists): It prints a string to the file pointed to by file pointer. The string can optionally include format specifiers and a list of variables variable lists.
Syntax:

pointer_variable =fopen(“file_name.txt”,”w”);
fputc(array_variable, pointer_variable);//if using loop
fputs("text or string", pointer_variable);//without loop

Example program for create the file and write data into the file:

#include <stdio.h>
#include<conio.h>
int main() {
        int i;
        FILE * fptr;//declare pointer variable to file
        char fn[50];
        char str[] = "C file hadling\n";
        fptr = fopen("file1.txt", "w"); // "w" defines "writing mode"
        for (i = 0; str[i] != '\n'; i++) {
            //write to file using fputc() function
            fputc(str[i], fptr);
        }
        fclose(fptr);//close the file
        return 0;
    }

Output:
Example program for w+ mode:

#include <stdio.h>
int main() {
        FILE * fp;
        fp = fopen("FILE1.txt", "w+");
        fputs("w+ is used to read and write operations.", fp);
        fputs("We don't need to use for loop\n", fp);
        fputs("Easier than fputc function\n", fp);
        fclose(fp);
        return (0);

Output:
How to read file:
  • Reading file is nothing but, it is used to show on the output screen to know what content inside the file.
Syntax:

 pointer_variable =fopen(“file_name.extention”,”r”);
while( variable_name  != EOF)
  {
    variable_name  = fgetc(pointer_variable);
  }

Example program for read file mode:

#include <stdio.h>
#include<conio.h>
int main()
{
  FILE *fr;
  char c;
  clrscr();
  fr = fopen("f2.c", "r");
  while( c != EOF)
  {
    c = fgetc(fr); // read from file
    printf("%c",c); //display on screen
  }
  getch();
  fclose(fr);
  return 0;
}

Output:
Example program for write and read program:

#include<stdio.h>
#include<conio.h>
int main()
{
   FILE *fp;
   char s[30];
   int n;
   clrscr();
   fp = fopen("output.txt", "w");
   printf("\n Enter a string and a number:\n");
   scanf("%s %d", s, &n); //read from keyboard
   fprintf(fp, "%s %d", s, n); // write to file
   fclose(fp);
   fp = fopen("output.txt", "r");
   printf("\n Read data from output.txt file..... \n");
   fscanf(fr, "%s\n%d", s, &n); //read from file
   printf("%s %d", s, n); //display on screen
  getch();
   fclose(fp);
   return 0;
}

Output:
How to append text into an existing file:
  • An append mode is nothing but, it similar to the write mode but it is used to concatenate the text already existing content.
  • Write mode is used to write new content into the file.
Syntax:

pointer_variable =fopen(file_name_stored_variable,’a’);
fprintf(fp, "%s\n", content_store_variable);// Write content to file
fclose(fp);//after write the content then close the file

Example:

#include <stdio.h>
#include<conio.h>
int main()
{
   FILE *fp;
   char ch;
   char *filename = "file1.txt";
   char *content = "This text is appended in file1 using C programming.";
   clrscr();
   fp = fopen(filename, "r");//first open and read file for display purpose
   printf("\n Before append text into the file : %s \n", filename);
   while ((ch = fgetc(fp) )!= EOF)
   {
      printf ("%c", ch);
   }
   fclose(fp);//closed after read
   fp = fopen(filename, "a");//again open for append
   fprintf(fp, "%s\n", content);// Write content to file
   fclose(fp);//after write the content then close the file
   fp = fopen(filename, "r");//again file open for read to check 
                                                                                    append or not
   printf("\n After append the text into the file %s \n", filename);
   while ((ch = fgetc(fp) )!= EOF)
   {
      printf ("%c", ch);
   }
   fclose(fp);//closed file
   getch();
   return 0;
}

Output:
Before running the program:
After running the program:
Share:

‘C’ pre-processor

The ‘C’ pre-processor:
  • These are placed before the main() function in the source program.
  • The pre-processor operates under the following pre-processor directives.
  1. File inclusion.
  2. Macro substitution.
  3. Conditional inclusion.
Rules for defining pre-processor:
  • Every pre-processor must start with the # symbol.
  • The pre-processor is always placed before the main() function.
  • The pre-processor cannot have termination with a semicolon.
  • There is no assignment operator in the #define statement.
  • The conditional macro must be terminated (#ifdef,#endif).
File inclusion:
This is used to include an external file, which contains functions or some other macro definitions to our source program, so we need not rewrite that functions and macros in our source program.
Syntax:

# include  <file_name>  and
# include “file_name”

Where,
<file_name>  is used searched only in standard directories.
“file_name” is used to search the file in your current directory and then in standard directories.

Program name: calc.c:

  1. int square(int x)

    {

              return x*x;

    }

    int cube(int x)

    {

              return x*x*x;

    }

Another program created for file inclusion:

  1. #include<stdio.h>

    #include "calc.c"

    void main()

    {

    int val;

    clrscr();

    printf("Enter a value: ");

    scanf("%d",&val);

    printf("Square root value is :%d",square(val));

    printf("\nCube value is :%d",cube(val));

    getch();

    }

Output:

Where,

“stdio.h” is the file, that contains standard input and output function ‘C’ standard directory.
“example.c” is the program written by the user, it frequently occurs in the main source program.
Macro substitutions:
  • This is used to define symbolic constants in the source program.
  • The identifier or string or integer defined is replaced by macro substitution.
  • This statement is also placed before the main() function in the source program.
Syntax:

i). Simple macro:
Syntax:
# define identifier string/integer 
Example:
#define A 20
ii). Argumented macros:
syntax:
#define identifier (v1 v2 v5...) string/integer

Example program:

#define sqr(n) n*n
#define cube(n) n*n*n
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=3,s,c;
clrscr();
s=sqr(a);
c=cube(b);
printf("\n Squre value of 5 is %d\n",s);
printf("\n Cube value of 3 is %d",c);
getch();
}

Output:
Conditional inclusion:
These are used to control the pre-processer with conditional statements.
Example program:

#define USD 1
#define UKP 1
#include<stdio.h>
#include<conio.h>
#ifdef USD
#define currency_rate 46
#endif
#ifdef UKP
#define currency_rate 100
#endif
void main()
{
int rs;
clrscr();
rs=10 * currency_rate;
printf("\n The value of rs is: %d\n",rs);
getch();
}

Output:

Share:

Memory allocation

Dynamic memory allocation:
  • Dynamic memory allocation means, a program can obtain its memory while it is running.
  •  It allows us to allocate additional memory space or release unwanted space (i.e. previously allocated) at the time of program execution (runtime).
  • The dynamic memory allocation is efficiently allowed to share the memory.
  • It is very useful to modify the size of the previous allocated memory.
Static memory:
  • So far, we have used static memory. Static memory means which reserve a certain amount of memory by default inside the program to use for variables and such.
  • It means that once reserve this memory, no other the program can use it, even if we are not using it at the time.
Dynamic memory allocation function:
  • Pointers support the dynamic memory allocation in ‘c’ language.
  • The ‘C’ language provides four library functions known as ‘Memory Management Function’ which can be used for allocating and realising memory during execution.
  • Any program, which uses these below functions, must be including the header file.
                                      #include<stdlib.h>
Example program:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char *p;//pointer variable
clrscr();
p=(char *) malloc(6);//allocate memory space to variable
strcpy(p,"MADRAS");
printf("\n Memory contains: %s\n",p);
p=(char *) realloc(p,7);//reallocation
strcpy(p,"CHENNAI");//string cpoy
printf("\n Memory now contains: %s\n",p);
free(p);// releasing memory
getch();
}

Output:
Share:

Pointers

Pointer:
  • The pointer is a variable and it is used to hold the address of another variable.
  • It is mainly used to allocate and De-allocate memory.
  • Each variable has two attributes: Address and value.
  • There are three elements in the pointer.

          * Pointer initialization
          * Pointer declaration
          * Pointer accessing data
Note:
  • & is an address operator.
  • * is the value operator for accessing pointer value.
  • %u is format specifiers for storing addresses.
  • A pointer data type is similar to the address of another variable data type.
Syntax for pointers:

Syntax for initializing pointer:
Data_type * variable_name;
Syntax for declaring pointer:
Pointer_varable=&address_of_another_vaiable;
Syntax for accessing the data by using pointer:
*pointer_variable =value(depend on requirements);

Example program for if:

#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,*p;//initialization
p=&a;//declaration
clrscr();
printf("\n Value of a is %d",a);
printf("\n address of a is %u",&a);
printf("\n  p value is %d",*p);
printf("\n  address of p is %u",&p);
*p=2+a;//accessing data
printf("\n Recent p value is %d",*p);
printf("\n Recent a value is %d",a);
getch();
}

Output:

Explanation:
Here using variable a is an int data type, the integer will have 2 bytes and hence the address of the next address element is incremented by 2.
Pointers and functions:
  • The pointer can be used as arguments in a function. The arguments or parameters to the function are passed in two ways.
Call by value
Call by reference
  • If you want to more detail about this topic, click the below link to learn this topic.
https://www.whereisstuff.com/2020/08/parameter-passing-methods-and-recursion.html

Array of pointers:
  • Array elements are always stored in consecutive memory locations according to the size of the array.
  • The size of the data type with the pointer variable refers to depends on the data type pointed by the pointer.
  • A pointer when incremented always points to a location after skipping the number of bytes required for the data type pointed toby it.
Example program array of pointers:

/* Program to sort a list of strings in alphabetical order using array of pointers*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void reorder(int a, char *x[]);//pointer with function
void main()
{
int i,a=0;
char *x[20];//array of pointer
clrscr();
printf("\n Enter each string on a separate line below.\n");
printf("\n Type \ 'END\' when finished.\n");
//read in the list of strings
do
{
x[a]=(char*) malloc(12 * sizeof (char));//allocate memory
printf("\n String %d: ",a+1);
scanf("%s",x[a]);
}
while(strcmp(x[a++],"END"));
//function calling  to reorder in the list of strings
reorder(--a,x);
printf("\n Reordered List of Strings: \n");
// display the reordered list of strings
for (i=0;i<a;++i)
printf("\n String %d: %s",i+1,x[i]);
getch();
}
// function definition
void reorder(int a,char *x[])
{
char *temp;//pointer variable to initialize
int i,y;
// Find lowest of all remaining strings
for(y=0;y<a-1;++y)
for (i=y+1;i<a;++i)
if (strcmp(x[y],x[i])>0)// compare the string for order
{
//interchanging the two strings
temp=x[y];
x[y]=x[i];
x[i]=temp;
}
return;
}

Output:
Structure of pointers:
  • A pointer pointing to a structure is known as pointers.
Example program:

#include<stdio.h>
#include<conio.h>
struct book
{
int book_no,bcost;
char *bname[20];
};
void main()
{
struct book p[3],*ptr;
clrscr();
printf("\n Enter three book of details....\n");
printf("\n Enter Book number, Name and Cost...\n");
for (ptr=p;ptr<p+3;ptr++)
scanf("%d%s%d",&ptr->book_no,ptr->bname,&ptr->bcost);
printf("\n STRUCTURE OUTPUT\n");
ptr=p;
while(ptr<p+3)
{
printf("%5d\t%-20s\t%d\n",ptr->book_no,ptr->bname,ptr->bcost);
ptr++;
}
getch();
}

Output:
Share:

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me