Thread: adding line numbers and concatenating a filename

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    15

    adding line numbers and concatenating a filename

    Hi-
    I'm brand new to the forum and C. I hope this hasn't already been answered. I searched and couldn't find anything, but I'm probably not looking properly. Anyway, I have an assignment in which we are supposed to take a command line argument that is the name of a text file and creates a new text file with a heading line and the contents of the original file w/line numbers added.
    If the filename contains a period, use the part of the name before before the period concatenated with .blah as the name of the new file, otherwise just concatenate .blah with the whole filename. Sorry if this is some newbie thing that I should have learned and offends you for asking but I'm lost, I can't get the filename or line numbers coded (truthfully, I haven't tried to hard on the line numbers ).
    Code:
    /*
     Goal is to make a backup of the file whose name is the first command line 
     argument. The second command line argument is the name of file. Prepend each
     new line with the line number and insert a 'title' heading at the top of the 
     new file (I call it backup) that was created.
     */
     
    #include <stdio.h>
    
    int main ( int argc, char *argv[], char ch, char *w, char *x )
    {
        if ( argc != 2 ) // argc should be 2 for correct execution 
        {
            // We print argv[0] assuming it is the program name 
            printf( "usage: %s <filename> (yes...you have to type a filename)", argv[0] );
        }
        else 
        {
            
            // Filename to open
            FILE *file = fopen( argv[1], "r" );
            //First file name to create
            w = argv[1];
            //Create the temporary new file (hopefully to be renamed later)
            FILE *newfile = fopen ("%s.blah", "w"); //doesn't work, simply creates %s.blah        //Add the new Heading to the file
            fprintf(newfile,"********************%s.blah******************\n\n\n\n", w);
            
            /* fopen returns 0, the NULL pointer, on failure */
            if ( file == 0 )
            {
                printf( "Could not open file\n" );
            }
            else 
            {
                /* read one character at a time from file, stopping at EOF, which
                   indicates the end of the file. */
                {
                    for (ch = getc(file);  ch != EOF;  ch = getc(file))
                    putc(ch, newfile);
                }
            }
            fclose( file );
            fclose( newfile );
        }
    }
    Hope the code posted correctly. Thank you for your time.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Um, you can't just change main()'s definition.

    Code:
    int main ( int argc, char *argv[])
    There. That is main()'s definition. If you want more variables, you declare them inside main().

  3. #3
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    so like this?
    Code:
    int main ( int argc, char *argv[])
    {
        char ch;
        char *w; 
        char *x;
    Thanks. Every little bit helps...

  4. #4
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Code:
    FILE *newfile = fopen ("&#37;s.blah", "w"); //doesn't work, simply creates %s.blah
    So it should,
    You need to put it in a buffer (%s is printf() syntax),
    Code:
    char buffer[256];
    sprintf(buffer, "%s.blah", argv[1]);
    
    ... fopen(buffer, "w");
    But make sure you won't overflow buffer, perhaps use strncat (C99) or strcat.

    > Um, you can't just change main()'s definition.
    Microsoft can , http://msdn.microsoft.com/en-us/libr...86(VS.60).aspx

    Here is one possible way of going around it (and probably what I'd do),
    * Read chunks of some size from the file (ie 1024 bytes) -- with fread()
    * Search this chunk for newline characters, write everything upto and including the newline character then a line number (then continue through the buffer until it's all gone / no more newline characters). Don't forget the first line starts with no newline character
    * Clap your hands, it's done
    Last edited by zacs7; 06-25-2008 at 06:33 AM. Reason: Ooops, I can't read.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I suggest you read the manual for fopen and fprintf, as well.
    And if fopen fails, it returns NULL, not 0.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    Zacs7 and Elysia-
    Thank you for the quick reply. Like I said, I'm new to programming period, and every little bit helps.

    Durrty

  7. #7
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    > Thank you for the quick reply. Like I said, I'm new to programming period, and every little bit helps.
    It was rather slow by this forums' standard.
    Do it step by step, that is -- don't try and write the entire program all at once.

    Read the file name;
    Parse the file name (append blah if need be, else pull out the name from before the '.');
    Open the files;
    etc.
    Last edited by zacs7; 06-25-2008 at 07:02 AM. Reason: Fragment, consider reversing.

  8. #8
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    Oh...well. It was quick to me, I wasn't expecting any response as I thought it was probably considered a dumb question.

    Thanks for the tips...

  9. #9
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    I still don't know what I'm doing. I can't construct a proper fgets() (if that's what I'm supposed to use to find each line) to get the lines one by one, then I have to insert line numbers. I'm not even going to talk about parsing the filename...argh!!!!

  10. #10
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    I'm really just venting...this site has been a tremendous help from the jump, so thanks, I'll continue to search and eventually find the answer...

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    So what have you tried (with respect to using fgets() for example)?

    There's been more than a few posts recently examplifying how you use fgets(), so they may be of help to you.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    Okay..here goes...lemme explain my thoughts first (please feel free to correct me, just not too harsh, a'ight :-). I know I need an output, the length (or an int) and ptr to the source. so the output is line, the length is LINE_LEN and the ptr is file...code is below:
    Code:
    #include <stdio.h>
    #include <string.h>
    #define LINE_LEN 80
    #define NAME_LEN 40
    
    int main ( int argc, char *argv[])
    {
        char ch;
        char *w; 
        char *status;
        char buffer[20];
        int i = 0;
        
        if ( argc != 2 ) // argc should be 2 for correct execution 
        {
            // We print argv[0] assuming it is the program name 
            printf( "usage: &#37;s <filename> (please type a filename)", argv[0] );
        }
        else 
        {
            FILE *file = fopen( argv[1], "r" );        // Filename to open
            w = argv[1];        //First file name to create
                    
            //Create the new file with *.blah extension
            sprintf(buffer, "%s.blah", argv[1]);
            FILE *newfile = fopen(buffer, "w");
            
            //Add the new Heading to the file
            fprintf(newfile,"********************%s.blah******************\n\n\n\n", w);
            
            /* fopen returns NULL, on failure */
            if ( file == NULL )
            {
                printf( "Could not open file\n" );
            }
            else 
            {
                /* read one character at a time from file, stopping at EOF, which
                   indicates the end of the file. */
                {
                    for (ch = getc(file);  ch != EOF;  ch = getc(file))
                    putc(ch, newfile);
                }
                    char line[LINE_LEN], linein[NAME_LEN],lineout[NAME_LEN];
                    for (status = fgets(line, LINE_LEN, file);
                         status != 0;
                         status  = fgets(line, LINE_LEN, file))
                         {
                           if (line[strlen(line) -1] == '\n') line[strlen(line) - 1] = '\0';
                           fprintf(newfile, "%3>> %s\n", ++i, line);
                         } 
            }
            fclose( file );
            fclose( newfile );
        }
    }
    Last edited by durrty; 06-27-2008 at 05:42 AM. Reason: spellcheck is your friend...

  13. #13
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    I dunno even know why I have NAME_LEN, it was part of the code that I copied...oops...

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
                {
                    for (ch = getc(file);  ch != EOF;  ch = getc(file))
                    putc(ch, newfile);
                }
    After this section, your file will be at EOF - so you can't read any more from the file without doing something about that.

    Code:
                    for (status = fgets(line, LINE_LEN, file);
                         status != 0;
                         status  = fgets(line, LINE_LEN, file))
    is correct, except that 0 should really be NULL, and you call fgets() in two places when you really only should do it the one place. A while-loop would be a better choice [same, obviously applies above when reading characters).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  15. #15
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    okay so I eliminated the extra fgets(). Should I try fseek() or something to correct the EOF problem?

Popular pages Recent additions subscribe to a feed