Search code examples
ctext-filesscanffgetsleading-zero

reading a file in C: leading zeros


In my program I'm trying to read two values per line from a textfile. It works well with my code below, but when I face numbers with leading zeros, it stores every zero as one value.

I want to be able to read in e.g. "007" as plain "7", but I still want to be able to read a "0" as a value.

Anyone could help me improving my code or point out what/where it could be improved?

thanks in advance

valuelist.txt

55 009
63 10
12 0

output

counter: 0 | Value A: 55 Value B: 0 
counter: 1 | Value A: 9 Value B: 0 
counter: 2 | Value A: 9 Value B: 0 
counter: 3 | Value A: 63 Value B: 0 
counter: 4 | Value A: 10 Value B: 0 
counter: 5 | Value A: 12 Value B: 0 
counter: 6 | Value A: 0 Value B: 0 

main

int main(void) {

        char name[] = "valuelist.txt";
        unsigned int counter = 0;
        unsigned int lines = 3;
        unsigned int num;
        unsigned int numtwo;


        FILE* ff = fopen(name,"r");
        if(ff == NULL) {
             fprintf(stderr, "Error \n");
            return -1;
        }

        char *tempp = (char*) malloc(lines + 1 );

        while(fgets(tempp,lines+1,ff) != NULL){

              sscanf(tempp,"%u %u",&num, &numtwo);

              printf("counter: %u | ",counter);
              printf("Value A: %u ",num);
              printf("Value B: %u \n",numtwo);

              counter++;
        }
        free(tempp);
        tempp = NULL;


return 0;
}

Solution

  • In your updated code and data, the problem is certainly that the value of lines is too small for your usage. You are using it to measure how much space you need for your tempp buffer, but that requires a maximum line width (plus one for the newline and another for the terminator). You are instead giving it a line count, and that of a file having only a few lines. Therefore fgets() is breaking up your lines across multiple calls.

    You indeed could pre-scan the file to find an appropriate width, then allocate that much, but you're going to a lot of trouble here to use fgets instead of fscanf. There are indeed reasons to prefer that for many problems, but yours does not look like one of them. You would save yourself considerable trouble and code by doing this instead:

    unsigned num, numtwo;
    while (fscanf(ff, "%u%u", &num, &numtwo) == 2) {
        // update counter, print results, etc...
    }