Skip to main content

Posts

Showing posts with the label File I/O in c language

C Program to Display its own Source Code as Output

  C program to display its own source code # include <stdio.h> int main () { FILE *fp; int c;     // open the current input file fp = fopen(__FILE__, "r" ); do { c = getc(fp); // read character putchar (c); // display character } while (c != EOF); // loop until the end of file is reached   fclose(fp); return 0 ; }

C Program to Read a Line From a File and Display it

  Program to read text from a file # include <stdio.h> # include <stdlib.h> // For exit() function int main () { char c[ 1000 ]; FILE *fptr; if ((fptr = fopen( "program.txt" , "r" )) == NULL ) { printf ( "Error! opening file" ); // Program exits if file pointer returns NULL. exit ( 1 ); } // reads text until newline is encountered fscanf (fptr, "%[^\n]" , c); printf ( "Data from the file:\n%s" , c); fclose(fptr); return 0 ; } If the file is found, the program saves the content of the file to a string  c  until  '\n'  newline is encountered. Suppose the  program.txt  file contains the following text in the current directory. C programming is awesome. I love C programming. How are you doing? The output of the program will be: Data from the file: C programming is awesome. If the file  program.txt  is not found, this program prints an error message.

C Program to Write a Sentence to a File

  This program stores a sentence entered by the user in a file. # include <stdio.h> # include <stdlib.h> int main () { char sentence[ 1000 ]; // creating file pointer to work with files FILE *fptr; // opening file in writing mode fptr = fopen( "program.txt" , "w" ); // exiting program if (fptr == NULL ) { printf ( "Error!" ); exit ( 1 ); } printf ( "Enter a sentence:\n" ); fgets(sentence, sizeof (sentence), stdin ); fprintf (fptr, "%s" , sentence); fclose(fptr); return 0 ; } Output Enter a sentence: C Programming is fun Here, a file named program.txt is created. The file will contain C programming is fun text.