Search code examples
cfopenfclose

Reading a file .txt in C with blank spaces


I trying to open a simple txt file in C, like the image bellow.

list example

The input text :

Name    Sex Age Dad Mom 
Gabriel M   58  George  Claire          
Louise  F   44          
Pablo   M   19  David   Maria

My doubt is, how can i make to identify the blank spaces in the list and jump correctly to another lines.

Here is my code:

#include <stdio.h>

int main() {
    FILE *cfPtr;

    if ((cfPtr = fopen("clients.txt", "r")) == NULL) {
        puts("The file can't be open");
    } else {
        char name[20];
        char sex[4];
        int age;
        char dad[20];
        char mom[20];
        char line[300];

    printf("%-10s%-10s%-10s%-10s%-10s\n","Name","Sex","Age","Dad","Mom");
    fgets(line,300,cfPtr);
    fscanf(cfPtr,"%10s%10s%d%12s%12s",name,sex,&age,dad,mom);

    while (!feof(cfPtr)) {
        printf("%-10s%-10s%d%12s%12s\n",name,sex,age,dad,mom);
        fscanf(cfPtr,"%19s%3s%d%12s%12s",name,sex,&age,dad,mom);
    }

        fclose(cfPtr);
    }
    return 0;
 }

It works fine if I fill in all the spaces...


Solution

  • printf("%-10s%-10s%d%12s%12s\n",name,sex,age,dad,mom);
    fscanf(cfPtr,"%19s%3s%d%12s%12s",name,sex,&age,dad,mom);
    

    Change the order to read first, print later.

    Ideally the data in your file should be separated by comma, tab, or some other character. If data is in fixed columns, then read everything as text (including integers) then convert the integer to text later.

    Also check the return value for fscanf, if the result is not 5 then some fields were missing.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h> 
    
    int main() 
    {
        FILE *cfPtr = fopen("clients.txt", "r");
        if(cfPtr == NULL) 
        {
            puts("The file can't be open");
            return 0;
        }
    
        char name[11], sex[11], dad[11], mom[11], line[300];
        int age;
    
        fgets(line, sizeof(line), cfPtr); //skip the first line
        while(fgets(line, sizeof(line), cfPtr))
        {
            if(5 == sscanf(line, "%10s%10s%10d%10s%10s", name, sex, &age, dad, mom))
                printf("%s, %s, %d, %s, %s\n", name, sex, age, dad, mom);
        }
    
        fclose(cfPtr);
        return 0;
    }
    

    Edit, changed sscan format to read integer directly, changed buffer allocation to 11 which is all that's needed.