Program to read an existing file.

Here, we have a basic program example to read an existing file using different languages. This program is created in c language, c++, Java, and Python.

Code to read an existing file in C language

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

void main()
{
	FILE *fptr;
	char fname[20];
	char str;
	printf(" Input the filename to be opened : ");
	scanf("%s",fname);
	fptr = fopen (fname, "r");
	if (fptr == NULL)
	{
		printf(" File does not exist or cannot be opened.\n");
		exit(0);
	}
	printf("\n The content of the file %s is  :\n",fname);
	str = fgetc(fptr);
	while (str != EOF)
		{
			printf ("%c", str);
			str = fgetc(fptr);
		}
	fclose(fptr);
    printf("\n\n");
}

Code to read an existing file in C++ language

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
   fstream newfile;
   newfile.open("new.txt",ios::in);
   if (newfile.is_open()){
      string tp;
      while(getline(newfile, tp)){
         cout <<"The data on the file is: "<<endl<< tp << "\n";
      }
      newfile.close();
   }
}

Code to read an existing file in Python language

file = open("Desktop/new.txt", "r")
read_content = file.read()
print("The contents of the file are: ")
print(read_content)

Code to read an existing file in Java language

import java.util.Scanner;
import java.io.*;
public class readfile
{
    public static void main(String[] args)
    {
        String fname;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the Name of File: ");
        fname = scan.nextLine();  
        String line = null;
        try
        {
            FileReader fileReader = new FileReader(fname);
            BufferedReader bufferedReader = new BufferedReader(fileReader);          
            while((line = bufferedReader.readLine()) != null)
            {
                System.out.println(line);
            }
            bufferedReader.close();
        }
        catch(IOException ex)
        {
            System.out.println("\nError occurred");
            System.out.println("Exception Name: " +ex);
        }
    }
}