Hi
I'm still learning programming in c and i have a problem with a program which is supposed to read the contents of a file specified in the command line argument and print the contents of the file in reverse order i.e. last line should come first , last but one line should come second so on ........Plz take a look at the code and let me know what is wrong with it.
Code:
# include <stdio.h>
# include <fcntl.h>
# include <stdlib.h>
# define _GNU_SOURCE
main(int argc, char *argv[])
{
int n = 0, nl;
FILE *fr, *fw;
char c;
char *line = NULL;
size_t len = 0;
ssize_t read;
if (argc < 2)
{
fprintf (stderr, "USAGE a.out <input filename> <outpt filename>\n");
exit (1);
}
fr = fopen (*++argv, "r"); /*file which is to be read*/
fw = fopen (*++argv, "w+"); /* output file which contains the result */
while ((c = fgetc (fr)) != EOF)
{
if (c == '\n')
n++; /* calculate the total number of line in file */
}
printf ("The total number of lines in the program are %d\n", n);
while ((read = getline (&line, &len, fr)) != -1)
{
printf ("Number of characters read in line is %d\n", read);
// printf ("%s", line);
fwrite (line, 1, read, fw);/*write the line to the output file */
lseek (fr, read, 1); /*set the file pointer to the previous line */
if (line)
free (line);
}
fclose (fr);
fclose (fw);
}