Tuesday, 23 June 2015

Write a C Program to read a file and display its content along with line number before each line.



#include<stdio.h>
main()
{
    FILE *fs;
    char ch;
    int i=1;
    fs=fopen("Hello.c","r");
    if(fs==NULL)
    {
        printf("can't open source file");
        exit(1);
    }
    printf("%d",i++);
    while(1)
    {
        ch=fgetc(fs);
        if(ch==EOF)
        {
            break;
        }
        printf("%c",ch);
        if(ch=='\n')
        {
            printf("%d",i);
            i++;
        }
    }
    fclose(fs);
}

OUTPUT
1#incluce<stdio.h>
2main()
3{
4       printf("Hello World");
5}
6

NOTE: First save "Hello.c" file