Question

I am having trouble loading this file.

The first number is how many characters/numbers will be in the subsequent sequences. I do not know/do not know how to figure out if these are numbers or characters.

Here is my code:

The text file is:

3
001
100    



 int main(int argc, char** argv)

{
    int  *array =0;
    array = LoadConfig(argv[1]);
    return 0;
}

int* LoadConfig(char * Filename)
{
    FILE* fptr = fopen(Filename, "r");
    int n=0; //number of rows
    int poles=0;
    int i=0; //for loop index
    int scanreturn; //error check
    scanreturn = fscanf(fptr, "%d", &n); // n will be the number of rows
    poles = n*n - n;
    int *array  =malloc(sizeof(int)*(poles));
    for(i=0;i<poles;i++)
    {
        scanreturn = fscanf(fptr, "%d", &array[i]);
        if (scanreturn !=1)
        {
            printf("danger\n");
        }
        printf("%d: %d\n",i, array[i]);
    }
    printf("%d is n  %d is poles\n",n, poles);
    return array;
}


the output is :0: 1
               1: 100
               danger
               2: 0
               danger
               3: 0
               danger
               4: 0
               danger
               5: 0
               3 is n  6 is poles

I'm guessing those are characters and not integers then?

Was it helpful?

Solution

1) Insure proper prototyping. Start with

#include <stdio.h>
#include <stdlib.h>
int* LoadConfig(char * Filename);

2) Only read 1 digit rather than unlimited digits - this is your main issue

// scanreturn = fscanf(fptr, "%d", &array[i]);
scanreturn = fscanf(fptr, "%1d", &array[i]);

3) Minor: Suggest as it is easier to maintain and more like calloc().

// int *array  =malloc(sizeof(int)*(poles));
int *array = malloc(poles * sizeof *array);

4) Be sure to free array in the calling routine when done with it.

free(array);
return 0;

5) Check fscanf() results

scanreturn = fscanf(fptr, "%d", &n);
if (scanreturn != 1) Oops();

6) Recommend fgets()/sscanf() or strtox() over fscanf()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top