user2785277
user2785277

Reputation: 345

Scanning integers from a file into an array in C?

I'm having trouble getting my program, which is meant to generate the Fibonacci sequence into a file and then read it back. I'm not sure if the r=problem lies in the scanning or printing, but I keep getting really long, wrong numbers

#include<stdio.h>

int main(){

    //Step 1
    int N;
    scanf(" %d", &N);

    if(N > 2){
        printf("You entered argument: %d\n", N);}
    else{
        printf("That is an illegal argument. N must be greater than 2.");
        return 0;}

    unsigned long a = 1;
    unsigned long b = 1;
    unsigned long c;
    int count = 2;

    FILE *fib;
    fib = fopen("Fibonacci", "w+");
    if (fib == NULL) {
        printf("Open TestFile failed\n");
        return -1;}


    fprintf(fib, "%lu %lu ",a,b);
    printf("%lu %lu ",a,b);
    for(count; count < N; count++){
        if(count % 4 == 0){
            fprintf(fib, "\n");
            printf("\n");}

        c = a+b;
        if(c < a){
            printf("integer overflow, ending number generation.");
            break;}
        fprintf(fib, "%lu ",c);
        printf("%lu ",c);
        a = b;
        b = c;
    }
    fflush(fib);
    printf("\ncount = %d",count);

    //Step 2

    unsigned long med;
    int middle;
    unsigned long nums[count];
    int j;
    if(count % 2 == 1){
        middle = (count/2);
        for(j = 0; j < count; j++){
            fscanf(fib, "%lu", &nums[j]);}
        med = nums[middle];
        printf("\nmedian = %lu", med);}


    unsigned long test1 = nums[0];
    unsigned long test2 = nums [1];
    unsigned long test3 = nums [2];
    printf("\nnums array: %lu %lu %lu",test1, test2, test3);


    return 0;
}

If input is 3, the output is

You entered argument: 3

1 1 2 

count = 3

median = 221891732872

nums array: 140733854067968 221891732872 26447888

Upvotes: 0

Views: 252

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148965

As noted by Johnny Mopp, you do not rewind the file, so in second step you are already at end of file when you read. If you had tested the return code of the different scanf, it would have been evident.

You should either close and reopen the file, or call

fseek(fib, 0L, SEEK_SET);

at the beginning of step 2

Anyway : always test the result of input functions.

Upvotes: 1

Thomas
Thomas

Reputation: 724

You can either :

  • Call rewind(fib); to reset your file pointer to the beginning of the file
  • Or, between steps 1 & 2, call fclose(fib);, and then re-open it with fopen("Fibonacci", "r");, in which case the first fopen call can simply have "w" as the second argument.

I'm not a big fan of the r+/w+ modes, and they don't have many uses in practice (imo), unless you're handling special files like /dev/mem or something.

See http://www.cplusplus.com/reference/cstdio/fopen/

Upvotes: 0

Related Questions