top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C program to count the number of lines in a text file and reverse the contents in the file to write in an output file?

0 votes
769 views

input:
one
two
three

output:
three
two
one

posted Jan 27, 2015 by Deepak Chitragar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes
#include<stdio.h>
#include<string.h>
main()
{
    FILE *fp1,*fp2;
    char a[100]="",total_line=0,temp1=0,temp2=0;

    fp1=fopen("text_file.txt","r");
    if(fp1==0)
    {
        printf("file %s is not found\n",text_file.txt); // If file does not exist then exit
        return;
    }

    fp2=fopen("new_text_file.txt","w+");
    while((fgets(a,sizeof(a),fp1))!=NULL)
       total_line++;  // Counting total lines

    fprintf(fp2,"Total lines = %d\n",total_line);
    rewind(fp1);
    bzero(a,sizeof(a));

    for(i=0;i<total_line;i++)
    {
        while((fgets(a,sizeof(a),fp1))!=NULL)
        {   
            temp1++;
            if(temp1==total_line)
                fputs(a,fp2); 
            bzero(a,sizeof(a));
        }

        rewind(fp2);
        temp1=++temp2;
    }
}
answer Jan 29, 2015 by Chirag Gangdev
0 votes

include <stdio.h>

include <stdlib.h> /* EXIT_SUCCESS */

int nextline (FILE *fpin, FILE *fpout)
{
char line[BUFSIZ];
static int n = 0;
if (fgets (line, BUFSIZ, fpin) != NULL)
{
n++;
nextline (fpin, fpout);
fprintf (fpout, "%s", line);
}
else
printf (" %d Lines counted\n", n);
}

int main (int argc, char *argv[])
{
FILE *src;
FILE *dest;

     if (argc != 3)
    {
        fprintf (stderr, "%s infilename outfilename\n", argv[0]);
        exit (EXIT_FAILURE);
    }

    if ((src = fopen (argv[1], "r")) == NULL)
    {
        perror (argv[1]);
        exit (EXIT_FAILURE);
    }
    if ((dest = fopen (argv[2], "w")) == NULL)
    {
        perror (argv[2]);
        exit (EXIT_FAILURE);
    }
    nextline (src, dest);
    return (EXIT_SUCCESS);
}
answer Apr 3, 2018 by anonymous
...