1

Prepping for PSET6 and trying to just load some ints from a file which has 100,000 integers. Easy to check and see for yourself (100K lines, all ints, all separated by a \n).

I'm running fscanf and it's only reading 54,044 integers. Can anyone help me understand what is going on?

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


int main (int argc, char *argv[])
{
    // check to see if you have the right parameters

    if (argc != 2)
    {
        printf("Usage: load[filename.txt]\n");
        return 1;
    }

    // get the file name and open the file

    const char *input = argv[1];

    int i = 0;

    while (strcmp(&input[i],"\0"))
        {
            printf("%c", input[i]);
            i++;
        }
    printf("\n");

    FILE *fp = fopen(input, "r");

    // count the number of integers

    int count = 0;
    fscanf(fp, "%i", &count);

    printf("Count is %i", count);



    return 0;
}

I'm not sure why fscanf would return the incorrect value? You can see I have checks (ie to make sure that I was copying the filename correctly). Read through the man pages and just not sure what's up.

Any help greatly appreciated. Thanks!

0

1 Answer 1

1

If you look at the first line of the file with the ints, you will see the number 54,044. That's because you are not reading all the ints in the file, only just the first, and that's what you print. If you want to read all the ints, put you fscanf() in a loop, like so:

int count = 0;
int tmp_number;
while (fscanf(fp, "%i", &tmp_number) == 1)  // if it hasn't read one item, it reached EOF
{
    printf("%d\n", tmp_number);
    count++;
}

printf("Count is %i", count);

extra tip

You should also add an

fclose(fp);

before return 0, so that you don't leak memory.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .