Search code examples
cfor-loopconcatenationc-stringsstrcat

C: Loop through struct and concat to string


I have C program with the following struct:

struct {      
    char *ext;
    char *filetype;
} extensions [] = {
    {"gif", "image/gif" },
    {"jpg", "image/jpg" },
    {"jpeg","image/jpeg"},
    {"png", "image/png" },
    {0,0}     
};            

How do I create a function that returns a string that contains only the extensions separated by new lines? Basically this is what to be able to do this:

printf("\nThe following extensions are supported:\n%s",GetExtensions());

And have it output this:

The following extensions are supported:
.gif
.jpg
.jpeg
.png

I think I've got the looping part correct, but I'm not understanding how to concat each ext + \n to a string:

#include <leaving these off for brevity...>

struct {
    char *ext;
    char *filetype;
} extensions [] = {
    {"gif", "image/gif" },
    {"jpg", "image/jpg" },
    {"jpeg","image/jpeg"},
    {"png", "image/png" },
    {0,0}     
};

char *getExtensions(void) {
    char* exts;
    int i;
    for(i=0;extensions[i].ext != 0;i++){

        // What do I do here?? 

    }
    return exts;
}

int main(int argc, char **argv){
    printf("\nThe following extensions are supported: \n%s",GetExtensions());
}

Solution

  • #include <stdio.h>
    #include <string.h>
    
    // Your struct
    struct extensionInfo {
       char *ext;
       char *filetype;
    };
    
    struct extensionInfo extensions [] = {
       {"gif", "image/gif" },
       {"jpg", "image/jpg" },
       {"jpeg","image/jpeg"},
       {"png", "image/png" },
       {0,0}
    };
    
    int main(int argc, char **args, char **env) {
       char buffer[1024];
       struct extensionInfo *ext;
    
       // Initialize the buffer
       memset(buffer, 0, sizeof(buffer));
    
       // Insert your first text.
       strncat(buffer, "The following extensions are supported:", sizeof(buffer) - 1);
    
       // Loop through your array and append everything
       for (ext = extensions; ext->ext != 0; ext++) {
          strncat(buffer, "\n", sizeof(buffer) - 1);
          strncat(buffer, ext->ext, sizeof(buffer) - 1);
       }
    
       // Show your result
       printf("%s\n", buffer);
    
       return 0;
    }
    

    Here is a commented example which works. If you have any questions, feel free to ask.