Tuesday, August 7, 2012

C Program To Print Lines From File

Below Given Is a Simple Program which prints the lines of a file but with different user given instructions.

The Feature of the Program is as Follows:

The Program Prints,

1) print first 10 lines of file

2) print last  20 lines of file

3) print all lines of file


#include <stdio.h>
#include <conio.h>
#include <process.h>
void main(int argc, char *argv[])
{
    int tot_lines,cnt;
    char *ptr;
    if( argc != 3 )
    {
        printf("\nInvalid number of arguments\n");
        return;
    }
    if( *argv[1] == '+' || *argv[1] == '-')
    {
        tot_lines = count_lines(argv[2]);
        ptr = argv[1];
        ptr++;  // skip '+' or '-'
        cnt = atoi(ptr);
        if ( cnt > tot_lines)
        {
            printf("\nInvalid line count\n");
            return;
        }
    }
    if( *argv[1] == '+' ) // typeline +cnt fname
        print_top_lines(argv[2],cnt);
    else
    if( *argv[1] == '-' ) // typeline -cnt fname
        print_bottom_lines(argv[2],cnt,tot_lines);
    else if (*argv[1]=='a')
        print_all_lines(argv[2]);
     else
         printf("\nInvalid option...");
} // main

int count_lines( char *fname)
{
    int tot_lines,ch;
    FILE *fp;
    char buff[80];
    fp = fopen(fname,"r");
    if( fp == NULL )
    {
        printf("\nUnable to open file");
        return(-1);
    }
    tot_lines = 0;
    while (fgets(buff,80,fp)!=NULL)
       tot_lines++;
    tot_lines++;
    fclose(fp);
    return(tot_lines);
} // count lines


int print_all_lines( char *fname)
{
    int ch;
    FILE *fp;
    char buff[80];
    fp = fopen(fname,"r");
    printf("\n");
    while(fgets(buff,80,fp)!=NULL)
     printf("%s",buff);

    fclose(fp);
    return;
} // print all lines

int print_top_lines(char *fname, int cnt)
{
    int curr_cnt;
    int ch;
    FILE *fp;
    char buff[80];

    curr_cnt = 0;

    fp = fopen(fname,"r");

    fgets(buff,80,fp);
    printf("\n");
    while( curr_cnt < cnt )
    {
        printf("%s",buff);
        fgets(buff,80,fp);
        curr_cnt++;
    }
    fclose(fp);
    return;
}
int print_bottom_lines(char *fname, int cnt, int tot_lines)
{
    int curr_cnt;
    int ch;
    FILE *fp;
    char buff[80];
    curr_cnt = 0;
    printf("\n");
    fp = fopen(fname,"r");
    while( 1)
    {
        fgets(buff,80,fp);
        curr_cnt++;
        if( curr_cnt >= tot_lines - cnt )
            break;
    }
    while( fgets(buff,80,fp) != NULL)
    {
        printf("%s", buff);
    }
    fclose(fp);
    return;
}

No comments:

Post a Comment

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...