C++ How to Read From a File

C read file

How to read a file in C? Y'all already know what a file is and their types (text/binary (audio/images/video etc.)). When a calculator is off, they are present on the hard disk.

Suppose you made a C plan last calendar week to sort numbers, and you wish to see the program again. How do you lot do it? You locate the file on the system and open information technology in an IDE/text editor. That is absurd! Merely what's more than interesting is to open the file through your program.

For simplicity, nosotros discuss reading text files only.

Allow'south write a C program to open a file from a hard deejay whose name is entered past a user and to display its contents on the screen. Opening a file means we bring the file contents from disk to RAM to perform operations (read/change/append a file) on information technology. The file must be present in the directory in which the executable file of the program exists.

Function fopen is used to open a file; it returns a pointer to construction FILE, which is a predefined structure in the "stdio.h" header file. If the file opening is successful, and then it returns a pointer to the file, and if it'southward unable to open up it, then it returns Zippo.

Function fgetc returns a graphic symbol read from the file, and the fclose function closes the file.

Read file in C using fopen

C programming code to open a file and print its contents on screen.

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

int master( )
{
char ch, file_name[ 25 ] ;
   FILE *fp;

printf ( "Enter name of a file y'all wish to run into\n" ) ;
gets (file_name) ;

   fp = fopen (file_name, "r" ) ; // read manner

if (fp == NULL)
{
perror ( "Error while opening the file.\due north" ) ;
go out (EXIT_FAILURE) ;
}

printf ( "The contents of %s file are:\due north" , file_name) ;

while ( (ch = fgetc (fp) ) != EOF)
printf ( "%c" , ch) ;

fclose (fp) ;
return 0 ;
}

Read file C program output:
C read file program output

Download Read file program.

There are bare lines present at the end of the file. In our program, we take opened only one file. You can open up multiple files in a single program, in different modes as required.

File handling is essential when we wish to shop data permanently on a storage device. All variables and data of a program are lost when it terminates. If the data is required later, we need to store information technology in a file.

cruzwiche1953.blogspot.com

Source: https://www.programmingsimplified.com/c-program-read-file

0 Response to "C++ How to Read From a File"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel