Read the content of File

Description

read the contents of sample.txt file and display it.

Solution

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fptr;
    char ch;
    char content[1000];
   
    
    fptr = fopen("sample.txt", "r");
    if (fptr == NULL)
    {
       printf("Cannot open file \n");
       return 0;
    }
    ch = fgetc(fptr);
    while (ch != EOF)
    {
        printf ("%c", ch);
        ch = fgetc(fptr);
    }
    fclose(fptr);
    return 0;
}

Explanation

fopen() to open the specified file. "sample.txt" is file name. "r" denotes open it in read mode.

fgetc() reads character by character from file.

Note: sample.txt should exsist  in the same folder where your program is located.



Interesting Pattern Programs: for more Patterns

Input:
5
Output:
*
**
***
****
*****
****
***
**
*Solution
Input:
5
Output:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *Solution
Input:
5
Output:
*        *
**      **
***    ***
****  ****
**********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********
**** ****
***   ***
**     **
*       *Solution
Input:
5
Output:
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********Solution

Related Programs