Search code examples
cscanfgets

Reading from a file and storing in C


I am trying to read in a text file of a string followed by a number and then store it's contents. So far I can only get it to print it out just the string (or just the int, or both) if it is properly formatted. How can I skip blank or misformatted lines lines (which currently duplicated the previous line) and also store the results?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"

#define MAX_LINE_LENGTH 400

int main ()
{
    char input[MAX_LINE_LENGTH];
    char name[MAX_LINE_LENGTH];
    int number;

    FILE *fr;
    fr = fopen ("updates.txt", "r");
    if (!fr)
    return 1;  
    while (fgets(input,MAX_LINE_LENGTH, fr)!=NULL)
    {
        /* get a line, up to 200 chars from fr.  done if NULL */
        sscanf (input, "%s", name);
        /* convert the string to just a string */
        printf ("%s\n", name);
    }
    fclose(fr);
    return 0;
}

Example text file

Cold 5
10 Flames

Doggy                      4

Flames 11
Cold 6

Solution

  • Probable solution for your problem is in the code below.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "list.h"
    
    #define MAX_LINE_LENGTH 400
    
    int main ()
    {
        char input[MAX_LINE_LENGTH];
        char name[MAX_LINE_LENGTH];
        char namet[MAX_LINE_LENGTH];
        int number;
    
        FILE *fr;
        fr = fopen ("updates.txt", "r");
        if (!fr)
        return 1;
        while (fgets(input,MAX_LINE_LENGTH, fr)!=NULL)
        {
            memset(name, 0, MAX_LINE_LENGTH);
            memset(namet, 0, MAX_LINE_LENGTH);
            /* get a line, up to 200 chars from fr.  done if NULL */
            //sscanf (input, "%s %d", name, &number);
            sscanf (input, "%s %s", name, namet);
    
            // TODO: compare here for name shall only contain letters A-Z/a-z
            // TODO: compare here for namet shall only contain digits
    
            // If both above condition true then go ahead
            number = atoi(namet);
    
            if(name[0] != '\0')
            {
                    /* convert the string to just a string */
                    printf ("%s %d\n", name, number);
                    //printf ("%s %s\n", name, namet);
            }
        }
        fclose(fr);
        return 0;
    }