C Program to Print Star Pyramid in File


This C program prints Star Pyramid in File to understand file handling more intuitively.


#include<stdio.h>
#include<stdlib.h>

int main()
{
 FILE *p;

 int i,j,n;
 char ch;

 p = fopen("pattern.txt", "w");

 if(p == NULL)
 {
  printf("File error!");
  getch();
  exit(1);
 }

 printf("Enter number of lines: ");
 scanf("%d", &n);
 fprintf(p, "***** STAR PYRAMID PATTERN *****\n\n");
 for(i=1;i<=n;i++)
 {

  for(j=1;j<=n-i;j++)
  {
   fprintf(p, " ");
  }
  for(j=1;j<=2*i-1;j++)
  {
   fprintf(p, "*");
  }
  fprintf(p, "\n");
 }

 fclose(p);

 printf("Please open pattern.txt to view pattern.");

 return 0;
}

Output of the above program

Enter number of lines: 12
Please open pattern.txt to view pattern.

And pattern.txt looks like:

***** STAR PYRAMID PATTERN *****

           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
***********************