Having problems returning a char* from a function..need help...

Discussion in 'C Programming' started by LongBow, Sep 12, 2003.

  1. LongBow

    LongBow Guest

    Hello all,

    From doing a google serach in the newsgroups I found out that a
    string can't be returned from a function, but using a char* I should
    be able to do it. I have spent most of the day trying to get this to
    work, but been unable to solve my mistake. What the function should
    return is a file name used for creating logs files. It will look
    something like

    JN122345.log

    JN - Month
    12 - Date
    23 - Hour
    45 - Min

    Can anyone provide any assistance, please. Thanks!.

    Mark


    --------- source code ------------

    #define MAX_TIME_LEN 6

    char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    "JL", "AG", "SP", "OC", "NV", "DC" };


    main( argc, argv )
    int argc;
    char *argv[];
    {
    char fileName[80];

    *sAutoBITELogFileName = getAutoBITELogFileName( );

    // Just seems to print only on character.
    _settextposition( 1,1 );
    printf( "lfn: '%s'", sAutoBITELogFileName );

    }



    char *getAutoBITELogFileName( )
    {
    /*----------------------------------------
    %d Day (01-31)
    %H Hour 24-hour style (00-23)
    %M Minute (00-59)
    ------------------------------------------*/

    time_t currentTime;
    struct tm* daynow;
    int iResult;
    char cTemp[ MAX_TIME_LEN + 1 ];
    char *fileName;

    /*sizeof *fileName is always 1, multiply by it anyway*/
    fileName = malloc( 13 * sizeof(*fileName) );

    if ( fileName == NULL ) {
    return NULL; // Problem allocating memory
    }

    currentTime = time(NULL); // get the current arithmetic calendar
    time

    // Convert the current arithmetic calendar time into local time held
    in a
    // structure of type tm.
    daynow = localtime(&currentTime);

    strncpy( fileName, cMonths[daynow->tm_mon], 2 );

    iResult = strftime(cTemp, MAX_TIME_LEN + 1, "%d%H%M", daynow);

    // Check to see if there was an error
    if ( iResult == 0 ) {
    return NULL;
    }

    strncat( fileName, cTemp, 6 );
    strncat( fileName, ".log", 4 );

    // Generally prints garbage, but some times can see the filename.
    _settextposition( 25, 1 );
    printf( "fn: %s", &fileName );

    return (char *)fileName;
    }
    LongBow, Sep 12, 2003
    #1
    1. Advertising

  2. LongBow <> wrote:

    >Hello all,
    >
    > From doing a google serach in the newsgroups I found out that a
    >string can't be returned from a function, but using a char* I should
    >be able to do it. I have spent most of the day trying to get this to
    >work, but been unable to solve my mistake. What the function should
    >return is a file name used for creating logs files. It will look
    >something like
    >
    >JN122345.log
    >
    > JN - Month
    > 12 - Date
    > 23 - Hour
    > 45 - Min
    >
    >Can anyone provide any assistance, please. Thanks!.
    >
    >Mark
    >
    >
    >--------- source code ------------

    /* You failed to include those: */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <time.h>

    >
    >#define MAX_TIME_LEN 6
    >
    >char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    > "JL", "AG", "SP", "OC", "NV", "DC" };
    >


    /* You failed to provide a prototype: */
    char *getAutoBITELogFileName( );

    >
    >main( argc, argv )
    > int argc;
    > char *argv[];

    int main( void ) /* you don't use argc and argv */

    >{
    > char fileName[80];

    /* You declare an array of characters without using it. */
    >
    > *sAutoBITELogFileName = getAutoBITELogFileName( );

    /* You failed to declare sAutoBITELogFileName. */

    >
    > // Just seems to print only on character.
    > _settextposition( 1,1 );

    /* Non-standard. No idea. */

    > printf( "lfn: '%s'", sAutoBITELogFileName );
    >

    /* You failed to return a value from a function
    declared to returning int: */

    return 0;
    >}
    >
    >
    >
    >char *getAutoBITELogFileName( )
    >{
    > /*----------------------------------------
    > %d Day (01-31)
    > %H Hour 24-hour style (00-23)
    > %M Minute (00-59)
    > ------------------------------------------*/
    >
    > time_t currentTime;
    > struct tm* daynow;
    > int iResult;
    > char cTemp[ MAX_TIME_LEN + 1 ];
    > char *fileName;
    >
    > /*sizeof *fileName is always 1, multiply by it anyway*/
    > fileName = malloc( 13 * sizeof(*fileName) );

    Magic number 13.

    >
    > if ( fileName == NULL ) {
    > return NULL; // Problem allocating memory
    > }
    >
    > currentTime = time(NULL); // get the current arithmetic calendar
    >time
    >
    > // Convert the current arithmetic calendar time into local time held
    >in a
    > // structure of type tm.
    > daynow = localtime(&currentTime);
    >
    > strncpy( fileName, cMonths[daynow->tm_mon], 2 );
    >
    > iResult = strftime(cTemp, MAX_TIME_LEN + 1, "%d%H%M", daynow);
    >
    > // Check to see if there was an error
    > if ( iResult == 0 ) {
    > return NULL;
    > }
    >
    > strncat( fileName, cTemp, 6 );
    > strncat( fileName, ".log", 4 );
    >
    > // Generally prints garbage, but some times can see the filename.
    > _settextposition( 25, 1 );

    Non-standard. No idea.

    > printf( "fn: %s", &fileName );

    printf( "fn: %s", fileName );

    >
    > return (char *)fileName;

    return fileName;

    >}



    Please read the faq-list for c.l.c at:
    http://www.eskimo.com/~scs/C-faq/top.html

    Irrwahn
    --
    Posting in usenet is like playing golf in a mine-field.
    Irrwahn Grausewitz, Sep 12, 2003
    #2
    1. Advertising

  3. LongBow

    T.M. Sommers Guest

    LongBow wrote:
    > Hello all,
    >
    > From doing a google serach in the newsgroups I found out that a
    > string can't be returned from a function, but using a char* I should
    > be able to do it. I have spent most of the day trying to get this to
    > work, but been unable to solve my mistake. What the function should
    > return is a file name used for creating logs files. It will look
    > something like
    >
    > JN122345.log
    >
    > JN - Month
    > 12 - Date
    > 23 - Hour
    > 45 - Min
    >
    > Can anyone provide any assistance, please. Thanks!.
    >
    > Mark
    >
    >
    > --------- source code ------------
    >
    > #define MAX_TIME_LEN 6
    >
    > char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    > "JL", "AG", "SP", "OC", "NV", "DC" };


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

    char *getAutoBITELogFileName( );

    To avoid the implicit int.

    > main( argc, argv )
    > int argc;
    > char *argv[];


    int main(int argc, char *argv[])

    > {
    > char fileName[80];
    >
    > *sAutoBITELogFileName = getAutoBITELogFileName( );
    >
    > // Just seems to print only on character.
    > _settextposition( 1,1 );


    Non-standard.

    > printf( "lfn: '%s'", sAutoBITELogFileName );


    printf( "lfn: '%s'\n", sAutoBITELogFileName );

    Add a newline to improve readability of the output.

    >
    > }
    >
    > char *getAutoBITELogFileName( )
    > {
    > /*----------------------------------------
    > %d Day (01-31)
    > %H Hour 24-hour style (00-23)
    > %M Minute (00-59)
    > ------------------------------------------*/
    >
    > time_t currentTime;
    > struct tm* daynow;
    > int iResult;
    > char cTemp[ MAX_TIME_LEN + 1 ];
    > char *fileName;
    >
    > /*sizeof *fileName is always 1, multiply by it anyway*/
    > fileName = malloc( 13 * sizeof(*fileName) );
    >
    > if ( fileName == NULL ) {
    > return NULL; // Problem allocating memory
    > }
    >
    > currentTime = time(NULL); // get the current arithmetic calendar
    > time
    >
    > // Convert the current arithmetic calendar time into local time held
    > in a
    > // structure of type tm.
    > daynow = localtime(&currentTime);
    >
    > strncpy( fileName, cMonths[daynow->tm_mon], 2 );
    >
    > iResult = strftime(cTemp, MAX_TIME_LEN + 1, "%d%H%M", daynow);
    >
    > // Check to see if there was an error
    > if ( iResult == 0 ) {
    > return NULL;
    > }
    >
    > strncat( fileName, cTemp, 6 );
    > strncat( fileName, ".log", 4 );
    >
    > // Generally prints garbage, but some times can see the filename.
    > _settextposition( 25, 1 );


    Non-standard.

    > printf( "fn: %s", &fileName );


    printf( "fn: %s\n", fileName );

    Add a newline, and you don't want to print the address of fileName,
    you want to print the contents. If you had turned all warnings on in
    your compiler, it should have caught this and the implicit ints.

    >
    > return (char *)fileName;


    The cast is redundant; fileName is already a char *.

    > }
    >
    T.M. Sommers, Sep 12, 2003
    #3
  4. "T.M. Sommers" <> wrote:
    >LongBow wrote:

    <BIG SNIP>
    >> printf( "fn: %s", &fileName );

    >
    > printf( "fn: %s\n", fileName );
    >
    >Add a newline, and you don't want to print the address of fileName,
    >you want to print the contents. If you had turned all warnings on in
    >your compiler, it should have caught this and the implicit ints.
    >

    If he had even tried to compile it, the compiler would have presented
    a fine (and long) list of errors and warnings, pointing out what is
    wrong.

    8^)

    Irrwahn

    --
    do not write: void main(...)
    do not cast the return value of malloc()
    do not fflush( stdin )
    read the c.l.c-faq: http://www.eskimo.com/~scs/C-faq/top.html
    Irrwahn Grausewitz, Sep 12, 2003
    #4
  5. LongBow

    LongBow Guest

    Irrwahn,

    Sorry, I cut and pasted for the purpose of this posting since I
    didn't want to include everything. I also failed to mention that I am
    using Microsoft C v6.00 and I am modifying an existing code base. So
    the main declaration is correct. The include files are there is the
    prototype in the header file, but not listed in the posting. The
    _settextposition sets the cursor position on the screen. When
    declaring fileName in the main, it should have been
    sAutoBITELogFileName, but I cut and paste the wrong item.

    Perhaps it is best to repost the code with the header files this
    time.. I hope this is better this time around.. sorry for the first
    bad posting..

    Mark





    --------- start main.h ---------------

    // Only relevant items listed for posting

    #include <stdio.h>
    #include <conio.h>
    #include <graph.h>
    #include <switches.h>
    #include <time.h>

    #define MAX_TIME_LEN 6

    char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    "JL", "AG", "SP", "OC", "NV", "DC" };

    --------- end main.h ---------------



    --------- start main.c ---------------

    // Only relevant items listed for posting

    #include "main.h"

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

    // Declare the Log File variable
    char sAutoBITELogFileName[80];

    // Current a log file name
    *sAutoBITELogFileName = getAutoBITELogFileName( );

    // Set the cursor position then print the resultant string
    _settextposition( 1,1 );
    printf( "lfn: '%s'", sAutoBITELogFileName );

    return 0;
    }



    char *getAutoBITELogFileName( )
    {
    /*----------------------------------------
    %d Day (01-31)
    %H Hour 24-hour style (00-23)
    %M Minute (00-59)
    ------------------------------------------*/

    time_t currentTime;
    struct tm* daynow;
    int iResult;
    char cTemp[ MAX_TIME_LEN + 1 ];
    char *fileName;

    /*sizeof *fileName is always 1, multiply by it anyway*/
    // DOS file name is 8 dot 3 for a total of 12 characters plus
    // a null terminating character. It will be defined later.

    fileName = malloc( 13 * sizeof(*fileName) );


    if ( fileName == NULL ) {
    return NULL; // Problem allocating memory
    }

    currentTime = time(NULL); // get the current arithmetic calendar
    time

    // Convert the current arithmetic calendar time into local time held
    in a
    // structure of type tm.
    daynow = localtime(&currentTime);

    strncpy( fileName, cMonths[daynow->tm_mon], 2 );

    // MAX_TIME_LEN is 6 since the format of the file name is
    MONTH/DATE/HOUR/MIN
    // which are all two character for a total of 8. So 8 minus two for
    the 6 with
    // a null terminating character.
    iResult = strftime(cTemp, MAX_TIME_LEN + 1, "%d%H%M", daynow);

    // Check to see if there was an error
    if ( iResult == 0 ) {
    return NULL;
    }

    strncat( fileName, cTemp, 6 );
    strncat( fileName, ".log", 4 );

    _settextposition( 25, 1 );
    printf( "fn: %s", fileName );

    return fileName;
    }

    --------- end main.c ---------------
    LongBow, Sep 12, 2003
    #5
  6. LongBow

    LongBow Guest


    >If he had even tried to compile it, the compiler would have presented
    >a fine (and long) list of errors and warnings, pointing out what is
    >wrong.
    >
    > 8^)



    No compiler errors, I do get two warnings at these points which are
    both

    '=' : different levels of indirection

    One in main at this point

    the other warning is point in between these two lines, not sure which
    one. I have compiled the project several times, but always in between
    these two lines..


    fileName = malloc( 13 * sizeof(*fileName) );
    <--- points here.....
    if ( fileName == NULL )


    I am not to sure what it means, but if someone does can you please
    tell me. thanks

    Mark
    LongBow, Sep 12, 2003
    #6
  7. LongBow

    LongBow Guest


    >If he had even tried to compile it, the compiler would have presented
    >a fine (and long) list of errors and warnings, pointing out what is
    >wrong.
    >
    > 8^)



    No compiler errors, I do get two warnings at these points which are
    both

    '=' : different levels of indirection

    One in main at this point

    *sAutoBITELogFileName = getAutoBITELogFileName( );


    the other warning is point in between these two lines, not sure which
    one. I have compiled the project several times, but always in between
    these two lines..


    fileName = malloc( 13 * sizeof(*fileName) );
    <--- points here.....
    if ( fileName == NULL )


    I am not to sure what it means, but if someone does can you please
    tell me. thanks

    Mark
    LongBow, Sep 12, 2003
    #7
  8. LongBow <> wrote:

    >Irrwahn,
    >
    > Sorry, I cut and pasted for the purpose of this posting since I
    >didn't want to include everything. I also failed to mention that I am
    >using Microsoft C v6.00 and I am modifying an existing code base. So
    >the main declaration is correct. The include files are there is the
    >prototype in the header file, but not listed in the posting. The
    >_settextposition sets the cursor position on the screen. When
    >declaring fileName in the main, it should have been
    >sAutoBITELogFileName, but I cut and paste the wrong item.
    >
    > Perhaps it is best to repost the code with the header files this
    >time.. I hope this is better this time around.. sorry for the first
    >bad posting..
    >
    >Mark
    >
    >--------- start main.h ---------------
    >
    >// Only relevant items listed for posting
    >
    >#include <stdio.h>


    >#include <conio.h>
    >#include <graph.h>
    >#include <switches.h>

    Well, posting code using non-standard extensions to the C language
    is still something that is frowned upon here in comp.lang.c.
    For example, my implementation does not provide these headers, so
    I have to delete all this stuff in order to compile your code ...

    >#include <time.h>

    #include <stdlib.h> /* for malloc() */
    #include <string.h> /* for strcpy() and strcat() */

    >
    >#define MAX_TIME_LEN 6
    >
    >char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    > "JL", "AG", "SP", "OC", "NV", "DC" };
    >
    >--------- end main.h ---------------
    >
    >
    >
    >--------- start main.c ---------------
    >
    >// Only relevant items listed for posting

    Unfortunately, not quite. ;-)

    Oh, and one more hint: single-line comments are likely to produce
    confusion in that they tend to produce funny effects when line
    wrapping occurs in the news-reader...

    >
    >#include "main.h"


    Provide a prototype for getAutoBITELogFileName():

    char *getAutoBITELogFileName();

    >
    >main( argc, argv )
    > int argc;
    > char *argv[];
    >{
    >
    > // Declare the Log File variable
    > char sAutoBITELogFileName[80];

    You allocate memory for the filename in getAutoBITELogFileName(), so:
    char *sAutoBITELogFileName;

    [ Or keep the array, assign the result of getAutoBITELogFileName() to
    a temporary variable, strcpy() the string to sAutoBITELogFileName
    and free() the memory you allocated using the temporary variable ]

    >
    > // Current a log file name
    > *sAutoBITELogFileName = getAutoBITELogFileName( );

    Get rid of the '*'.

    <SNIP>

    After performing a quick clean-up, your code looks like this:

    /************************************************/

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

    #define MAX_TIME_LEN 6

    char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    "JL", "AG", "SP", "OC", "NV", "DC" };

    /* provide a prototype for getAutoBITELogFileName() */
    char *getAutoBITELogFileName();

    int main( )
    {
    char *sAutoBITELogFileName;

    sAutoBITELogFileName = getAutoBITELogFileName( );

    printf( "lfn: '%s'", sAutoBITELogFileName );
    fflush( stdout );
    return 0;
    }

    char *getAutoBITELogFileName( )
    {
    time_t currentTime;
    struct tm* daynow;
    int iResult;
    char cTemp[ MAX_TIME_LEN + 1 ];
    char *fileName;

    /*sizeof *fileName is always 1, multiply by it anyway
    DOS file name is 8 dot 3 for a total of 12 characters plus
    a null terminating character. It will be defined later. */

    fileName = malloc( 13 * sizeof(*fileName) );

    if ( fileName == NULL ) {
    return NULL; /* Problem allocating memory */
    }

    /* get the current arithmetic calendar time */
    currentTime = time(NULL);

    /* Convert the current arithmetic calendar time into local
    time held in a structure of type tm. */
    daynow = localtime(&currentTime);

    strncpy( fileName, cMonths[daynow->tm_mon], 2 );

    /* MAX_TIME_LEN is 6 since the format of the file name is
    MONTH/DATE/HOUR/MIN which are all two character for a
    total of 8. So 8 minus two for the 6 with a null
    terminating character.*/

    iResult = strftime(cTemp, MAX_TIME_LEN + 1, "%d%H%M", daynow);

    /* Check to see if there was an error */
    if ( iResult == 0 ) {
    return NULL;
    }

    strncat( fileName, cTemp, 6 );
    strncat( fileName, ".log", 4 );

    printf( "fn: %s ", fileName );

    return fileName;
    }

    /************************************************/

    IMHO, this version should be fairly portable and AFAICS works fine,
    though I have not tested it thoroughly. However, there is still room
    for some improvements, but unfortunately I have to go and get some
    sleep right now, but hopefully someone else will take over at this
    point...

    Regards

    Irrwahn
    --
    Zzzzzzzzzzz-Roooooooon
    Irrwahn Grausewitz, Sep 12, 2003
    #8
  9. LongBow

    LongBow Guest

    Irrwahn,

    The solution you provide didn't work fully, but compiled without
    warning nor errors, but it was still returning a bad string value.
    After several hours I have a working version, but testing is still
    needed and I may have tweak it since I got a solution working Visual
    C++ v6.0. I need the IDE to trace through the code to see what was
    going on. There is one important note in the documentation that
    pointed me in the right direction since I was seeing the char strings
    larger than what I was specifying during allocation.

    ---- Taken from MSDN April 2001 under 'malloc' ----
    Remarks
    The malloc function allocates a memory block of at least size bytes.
    The block may be larger than size bytes because of space required for
    alignment and maintenance information.

    Since the malloc was creating a memory block and larger than I
    specified. In addition the memory block was fully of junk so during
    the string operation it wasn't finding the NULL character in the
    correct locations. So I needed to clear the memory block. At first I
    was using _strset, but it was causing access violation when the heap
    was freed. I found the function memset which allows me to specify the
    length. Thanks for the help and pointing me in the right direction.
    Sorry for posting in the wrong group, but I couldn't find another
    group under microsoft.public.* domain, at least what my ISP news
    servers list. I figure people wouldn't mind.....

    Mark


    here is what I have thus far for those who want to see. Compile and
    ran under Visual C++ v6.0 ( VS 97 )....



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


    #define MAX_TIME_LEN 6
    #define MAX_FILE_NAME_LENGTH 12
    #define FILE_NAME_EXT ".log"

    char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    "JL", "AG", "SP", "OC", "NV", "DC" };

    /* provide a prototype for getAutoBITELogFileName() */
    int getAutoBITELogFileName( char *fileName );



    int main( )
    {
    char *sAutoBITELogFileName;
    int iResult;

    sAutoBITELogFileName = malloc( MAX_FILE_NAME_LENGTH + 5 );
    _strset( sAutoBITELogFileName, 0 );

    iResult = getAutoBITELogFileName( sAutoBITELogFileName );


    printf( "lfn: '%s'\n\n", sAutoBITELogFileName );
    fflush( stdout );
    return 0;
    }



    int getAutoBITELogFileName( char *fileName )
    {
    time_t currentTime;
    struct tm* daynow;
    int iResult;
    char cTemp[ MAX_TIME_LEN + 1 ];
    char *tempFileName;

    /*sizeof *fileName is always 1, multiply by it anyway
    DOS file name is 8 dot 3 for a total of 12 characters plus
    a null terminating character. It will be defined later. */

    tempFileName = malloc( MAX_FILE_NAME_LENGTH + 1 );

    memset( tempFileName, 0, MAX_FILE_NAME_LENGTH + 1 );
    memset( cTemp, 0, MAX_TIME_LEN + 1 );

    if ( tempFileName == NULL ) {
    return 0; /* Problem allocating memory */
    }

    /* get the current arithmetic calendar time */
    currentTime = time(NULL);

    /* Convert the current arithmetic calendar time into local
    time held in a structure of type tm. */
    daynow = localtime(&currentTime);

    strncpy( tempFileName, cMonths[daynow->tm_mon], 2 );

    /* MAX_TIME_LEN is 6 since the format of the file name is
    MONTH/DATE/HOUR/MIN which are all two character for a
    total of 8. So 8 minus two for the 6 with a null
    terminating character.*/

    iResult = strftime(cTemp, MAX_TIME_LEN + 1, "%d%H%M", daynow);

    /* Check to see if there was an error */
    if ( iResult == 0 ) {
    return 0;
    }

    strncat( tempFileName, cTemp, MAX_TIME_LEN );
    strncat( tempFileName, FILE_NAME_EXT, sizeof( FILE_NAME_EXT ) );
    strcpy( fileName, tempFileName );

    iResult = strlen( tempFileName );
    free( tempFileName );

    return iResult;

    }
    LongBow, Sep 12, 2003
    #9
  10. LongBow

    Tom Zych Guest

    LongBow wrote:

    > main( argc, argv )
    > int argc;
    > char *argv[];
    > {


    This style of function definition, though still supported, has been
    obsolete for about 15 years. What book did you learn this from?

    --
    Tom Zych
    This email address will expire at some point to thwart spammers.
    Permanent address: echo '' | rot13
    Tom Zych, Sep 12, 2003
    #10
  11. LongBow <> wrote:

    <SNIP>
    > Since the malloc was creating a memory block and larger than I
    >specified. In addition the memory block was fully of junk so during
    >the string operation it wasn't finding the NULL character in the
    >correct locations.

    Hm, I should have noticed ...

    <SNIP>
    > Thanks for the help and pointing me in the right direction.
    >Sorry for posting in the wrong group, but I couldn't find another
    >group under microsoft.public.* domain, at least what my ISP news
    >servers list. I figure people wouldn't mind.....


    You weren't posting in the wrong group, my point was that your code
    consisted of non-standard extension some people here are allergic to,
    and rightfully so. So: if your code won't work first strip off the
    non-standard extensions; if the problem persists, cut it down to a
    minimalist version, still showing the problem; then feel free to post
    it here.

    >
    >here is what I have thus far for those who want to see. Compile and
    >ran under Visual C++ v6.0 ( VS 97 )....
    >

    <SNIP>

    Compiled with MingW32-gcc3.2 and run under W2K as well.
    Looks good now. :)

    Irrwahn

    --
    do not write: void main(...)
    do not use gets()
    do not cast the return value of malloc()
    do not fflush( stdin )
    read the c.l.c-faq: http://www.eskimo.com/~scs/C-faq/top.html
    Irrwahn Grausewitz, Sep 12, 2003
    #11
  12. LongBow

    Al Bowers Guest

    LongBow wrote:
    > Irrwahn,
    >
    > The solution you provide didn't work fully, but compiled without
    > warning nor errors, but it was still returning a bad string value.
    > After several hours I have a working version, but testing is still
    > needed and I may have tweak it since I got a solution working Visual
    > C++ v6.0. I need the IDE to trace through the code to see what was
    > going on. There is one important note in the documentation that
    > pointed me in the right direction since I was seeing the char strings
    > larger than what I was specifying during allocation.
    >


    ...........snip........

    >
    > #include <stdio.h>
    > #include <stdlib.h>
    > #include <string.h>
    > #include <time.h>
    >
    >
    > #define MAX_TIME_LEN 6
    > #define MAX_FILE_NAME_LENGTH 12
    > #define FILE_NAME_EXT ".log"
    >
    > char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    > "JL", "AG", "SP", "OC", "NV", "DC" };
    >


    code snipped

    >
    > strncpy( tempFileName, cMonths[daynow->tm_mon], 2 );
    >


    ...........snipped,,,,,,,,,,

    You are repeating the same problem that is in the code provided by
    Irrwahn.

    There are two problems with the strncpy statement. First, the elements
    in the array cMonths are not strings. The second argument strncpy
    expects a string. Second, since the argument 2 == the length of the
    second argument a nul-terminating char is not appended.

    The solution is simple.
    change the array declaration to:

    char cMonths[12][3] = { "JN", "FB", "MR", "AP", "MY", "JU",
    "JL", "AG", "SP", "OC", "NV", "DC" };

    This gives enough room to a nul (string ending character) which
    is automatically included.
    And change the strncpy to strcpy.

    strcpy( tempFileName, cMonths[daynow->tm_mon]);

    The corrected code:

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

    #define MAX_TIME_LEN 6

    char cMonths[12][3] = { "JN", "FB", "MR", "AP", "MY", "JU",
    "JL", "AG", "SP", "OC", "NV", "DC" };

    char *getAutoBITELogFileName(void);

    int main(void )
    {
    char *sAutoBITELogFileName;

    sAutoBITELogFileName = getAutoBITELogFileName( );
    printf( "lfn: '%s\n", sAutoBITELogFileName );
    free(sAutoBITELogFileName); /* Free memory when finished */
    return 0;
    }

    char *getAutoBITELogFileName(void )
    {
    time_t currentTime;
    struct tm* daynow;
    int iResult;
    char cTemp[ MAX_TIME_LEN + 1 ];
    char *fileName;

    fileName = malloc( 13 * sizeof(*fileName) );
    if ( fileName == NULL )
    return NULL; /* Problem allocating memory */
    currentTime = time(NULL);
    daynow = localtime(&currentTime);
    strcpy( fileName, cMonths[daynow->tm_mon]);
    iResult = strftime(cTemp, MAX_TIME_LEN + 1, "%d%H%M", daynow);
    if ( iResult == 0 )
    return NULL;
    strcat( fileName, cTemp );
    strcat( fileName, ".log" );
    printf( "fn: %s\n", fileName );
    return fileName;
    }


    --
    Al Bowers
    Tampa, Fl USA
    mailto: (remove the x)
    http://www.geocities.com/abowers822/
    Al Bowers, Sep 12, 2003
    #12
  13. Al Bowers <> wrote:
    >
    >LongBow wrote:

    ...........snip........
    >>
    >> char cMonths[12][2] = { "JN", "FB", "MR", "AP", "MY", "JU",
    >> "JL", "AG", "SP", "OC", "NV", "DC" };

    >code snipped
    >>
    >> strncpy( tempFileName, cMonths[daynow->tm_mon], 2 );
    >>

    >..........snipped,,,,,,,,,,
    >
    >You are repeating the same problem that is in the code provided by
    >Irrwahn.
    >
    >There are two problems with the strncpy statement. First, the elements
    >in the array cMonths are not strings. The second argument strncpy
    >expects a string. Second, since the argument 2 == the length of the
    >second argument a nul-terminating char is not appended.


    Uh-oh. I just bought a new pair of glasses and still I'm blind...

    >
    >The solution is simple.
    >change the array declaration to:
    >
    >char cMonths[12][3] = { "JN", "FB", "MR", "AP", "MY", "JU",
    > "JL", "AG", "SP", "OC", "NV", "DC" };
    >
    >This gives enough room to a nul (string ending character) which
    >is automatically included.
    >And change the strncpy to strcpy.
    >
    >strcpy( tempFileName, cMonths[daynow->tm_mon]);
    >

    <SNIP>
    That looks more C-like now, definitely!

    --
    do not write: void main(...)
    do not use gets()
    do not cast the return value of malloc()
    do not fflush( stdin )
    read the c.l.c-faq: http://www.eskimo.com/~scs/C-faq/top.html
    Irrwahn Grausewitz, Sep 12, 2003
    #13
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. wwj
    Replies:
    7
    Views:
    537
  2. wwj
    Replies:
    24
    Views:
    2,477
    Mike Wahler
    Nov 7, 2003
  3. Ben Pfaff
    Replies:
    5
    Views:
    458
    Tristan Miller
    Jan 17, 2004
  4. Replies:
    8
    Views:
    524
    Bryan Donlan
    Aug 26, 2005
  5. lovecreatesbeauty
    Replies:
    1
    Views:
    1,007
    Ian Collins
    May 9, 2006
Loading...

Share This Page