j.DOH j.DOH - 25 days ago 10
C Question

How to join char arrays in c

so I have a text file which has the name of channels, in this format:

General
Private
Programming
Calculus


And what I'm trying to do is if the user writes '/channels' on the console the program is supposed to print all the channels in this format:

Channels are : General, Private, Programming, Calculus


My problem is printing the channels in this format, with the commas separating them. With what I have now I can printf the channels but they are printed in the format that they have in the text file (one channel name per line). If someone could maybe explain to me what the optimal way for doing this is I would be very thankful. Here is the code I currently have for printing the channels:

void get_channels() {
char tmp[50];
FILE *f;
f = fopen("../1part/channels.txt", "r");
if (f == NULL) { perror("Mistake reading: "); exit(1); } ;
while (fgets(tmp, sizeof(tmp), f)) {
printf("%s", tmp);
}

fclose(f);
}

Answer

You should strip the trailing newline from the line read by fgets().

void get_channels(void) {
    char tmp[50];
    FILE *f;
    const char *separator = "";

    f = fopen("../1part/channels.txt", "r");
    if (f == NULL) {
        perror("Mistake reading: ");
        exit(1);
    }
    printf("Channels are: ");
    while (fgets(tmp, sizeof(tmp), f)) {
        /* strip the newline character if present */
        tmp[strcspn(tmp, "\n")] = '\0';
        printf("%s%s", separator, tmp);
        separator = ", ";
    }
    printf("\n");

    fclose(f);
} 

Notes:

  • if the file does not end with a newline, removing the last character of the line would not work correctly.
  • if a line in the file is longer than 49 characters, tmp will not end with a linefeed either. Stripping the last character would be incorrect too, but the above code still mishandles this case as such a line will be split into 2 items. Making the buffer larger is a simple solution.
  • the separator string is output before each item, initializing it to the empty string and changing it to ", " after each item is a simple method to produce a joined list without an extra test.