Chapter - 13: File Input-Output

Write a program to read a file and display contents with its line numbers.


C
Sections
1
Exercises

A

B

C

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

File (a).txt

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

 

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
	FILE *fp;
	int i = 1;
	char ch;
	fp = fopen("File (a).txt", "r+");
	if (fp == NULL)
	{
		puts("\nFile can't be open");
		exit(1);
	}
	/*Line no. before first line*/
	printf("%d. ", i);
	i++;
	do
	{
		ch = fgetc(fp);
		if (ch == '.')
		{
			printf("%c", ch);
			if (fgetc(fp) == EOF)
				continue;

			/*Printing the line number*/
			printf("\n%d. ", i);

			i++;
			continue;
		}
		printf("%c", ch);
	} while (ch != EOF);
	fclose(fp);
	_getch();
	return 0;
}

© 2020 Garbage Valuegarbage value logo