writing formatted data of unknown length to a string (C programming)

后端 未结 5 1045
Happy的楠姐
Happy的楠姐 2020-12-31 11:36

The following C function:

int sprintf ( char * str, const char * format, ... );

writes formatted data to a string. The size of the array pa

5条回答
  •  自闭症患者
    2020-12-31 12:04

    I threw this together as an exercise for myself based on DigitalRoss' suggestion. Feel free to merge this with his answer if you have the rep (I don't).

    #include 
    #include 
    #include 
    #include 
    
    char* createRandstr(void);
    
    int main(void)
    {
        char* mystr;
        char* randomString;
        size_t len;
    
        /* Makes a random string of A's */
        randomString = createRandstr();
    
        /* 1st pass gets needed size */
        len = (size_t)snprintf(NULL, 0, "random string -->%s<--\n", randomString);
        mystr = malloc(len);
    
        /* Safely write to mystr with known length 'len' */
        snprintf(mystr, len, "random string -->%s<--\n", randomString);
        puts(mystr);
    
        free(mystr);
        free(randomString);
    
        return 0;
    }
    
    char* createRandstr(void)
    {
        char*  randstr;
        size_t randlen;
        unsigned int i;
    
        srand((unsigned int)time((time_t*)NULL)); /* Seed rand() */
        randlen = (size_t)rand() % 50; /* Limit to max of 49 chars */
        randstr = malloc(randlen);
    
        for (i=0; i < randlen; i++)
        {
            randstr[i] = 'A';
        }
        randstr[randlen - 1] = '\0';
    
        return randstr;
    }
    

提交回复
热议问题