Showing posts with label Files I/O. Show all posts
Showing posts with label Files I/O. Show all posts

C program to display its own source code as output

PROGRAM:



#include <stdio.h>
int main()
 {
    FILE *fp;
    char c;
    fp = fopen(__FILE__,"r");
    do 
      {
         c = getc(fp);
         putchar(c);
       }
    while(c != EOF);
    fclose(fp);
    return 0;
}

MASTER OTHER EXAMPLES:



C program to read a line from a file and display it

PROGRAM:

 
#include <stdio.h>
#include <stdlib.h> 
int main()
{
    char c[1000];
    FILE *fptr;
 
    if ((fptr = fopen("program.txt", "r")) == NULL)
    {
        printf("Error! opening file");
        exit(1);         
    }
 
    fscanf(fptr,"%[^\n]", c);
 
    printf("Data from the file:\n%s", c);
    fclose(fptr);
    
    return 0;
}


NOTICE:

The file program.txt should be created otherwise it prints an error message


MASTER OTHER EXAMPLES:


C program to write a sentence to a file

PROGRAM:



#include <stdio.h>
#include <stdlib.h> 
int main()
{
   char sentence[1000];
   FILE *fptr;

   fptr = fopen("program.txt", "w");
   if(fptr == NULL)
   {
      printf("Error!");
      exit(1);
   }
  
   printf("Enter a sentence:\n");
   gets(sentence);

   fprintf(fptr,"%s", sentence);
   fclose(fptr);

   return 0;
}

OUTPUT:

Enter sentence:
I am awesome and so are files.

MASTER OTHER EXAMPLES: