Quantcast
Channel: DaniWeb Solved Topics
Viewing all articles
Browse latest Browse all 587

A program to list a code listing (beginner stuff

$
0
0

I just started learning C with a book called "Sams | Teach Yourself C in 21 Days, 6th edition" and I've already run into a problem I can't solve. The book gives a program that is supposed to display any code from any saved source file - including its own. As the book states on page 37, "The list_it.c program in Listing 2.2 displays C program listings that you have saved. These listings are displayed on the screen with line numbers added."

The problem is that I don't know how to use it to make it work and the book doesn't give any specific instructions for using it. What am I supposed to do with it? I'm using Dev C++ and when I run it all I get is this:

            Proper Usage is:

            list_it filename.ext

I've tried renaming and recompliling this program with two different filenames - list_it multiply.c and list_it list_it.c and it just gave me scrambled junk. I've also tried opening multiply.c and using the same approach and I got the same result.
Here's the code:

/* list_it.c - This program displays a listing with line numbers! */

#include <stdio.h>
#include <stdlib.h>

void display_usage(void);
int line;

int main( int argc, char *argv[] )
{
    char buffer[256];
    FILE *fp;

    if(argc < 2)
    {
        display_usage();
        return 1;
    }

    if (( fp = fopen( argv[1], "r" )) == NULL )
    {

        fprintf( stderr, "Error opening file, %s!", argv[1] );
        return(1);

    }

    line = 1;

    while( fgets( buffer, 256, fp ) != NULL )
        fprintf( stdout, "%4d:\t%s", line++, buffer );

    fclose(fp);
    return 0;

}   

void display_usage(void)
{
    fprintf(stderr, "\nProper Usage is: " );
    fprintf(stderr, "\n\nlist_it filename.ext\n" );
}

Viewing all articles
Browse latest Browse all 587

Trending Articles