Read a Line From a File in C

C read file

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

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

For simplicity, we discuss reading text files only.

Let's write a C program to open up a file from a hard disk whose proper noun 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/alter/append a file) on it. 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; information technology returns a arrow to structure 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's unable to open it, then information technology returns NULL.

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

Read file in C using fopen

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

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

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

printf ( "Enter name of a file you wish to see\n" ) ;
gets (file_name) ;

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

if (fp == Goose egg)
{
perror ( "Fault while opening the file.\n" ) ;
get out (EXIT_FAILURE) ;
}

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

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

fclose (fp) ;
return 0 ;
}

Read file C programme output:
C read file program output

Download Read file program.

There are bare lines present at the end of the file. In our plan, nosotros have opened but one file. You tin can open multiple files in a unmarried program, in dissimilar 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 after, we need to store it in a file.

wellsbrieforetwor.blogspot.com

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

0 Response to "Read a Line From a File in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel