Max Denner Max Denner - 2 days ago 5
C Question

Formatting my data from a file;

This is how the data file looks.

strain condition exp.no t6 t24
ST1 wt exp1 1.77 7.60
ST1 wt exp2 1.58 7.39
ST1 wt exp3 1.78 7.57
ST1 wt exp4 1.82 7.60
ST1 wt exp5 1.59 7.59


I want to print the data as such:-

strain-----condition-----exp.no----t6--------t24
ST1-------wt--------------exp1------1.77----7.60
ST1-------wt--------------exp2------1.58----7.39
ST1-------wt--------------exp3------1.78----7.57
ST1-------wt--------------exp4------1.82----7.60
ST1-------wt--------------exp5------1.59----7.59


With the dashes representing spaces. I only managed to print the lines as strings individually and have no idea how format it as such.

#include <stdio.h>
#include <stdlib.h>
int main()
{
char DATA[1024];
FILE *fbacteria;


if ((fbacteria = fopen("bacteria.exp", "r")) == NULL)
{
printf("Error! opening file");
exit(1);
}

while(!feof(fbacteria)){

fgets(DATA,1024,fbacteria);
puts(DATA);
}
fclose(fbacteria);

return 0;
}

Answer

Here's a function to print a string, replacing every space with 7 dashes:

void printDash(char *line)
{
    while (*line) {
        if (*line == ' ')
            printf("-------");
        else
            putchar(*line);
        *line++;
    }
}

You might call it like this:

int main(void)
{
    FILE *f = fopen("somefile.txt", "r");
    char s[1024];

    while (fgets(s, 1024, f))  // loop through every line in the file
        printDash(s);          // print each line, replacing each space with dashes

    fclose(f);
    return 0;
}
Comments