سؤال

i am trying to sipmply input some data into a struct from a file. I have used the same excact code in a different program and it works as it should? I dont know where i am wrong. Shouldnt the code below work ? Maybe i am not that familiar with sscanf .I would like some help. Thank you.

The txt file is like this:
foo.var 1241
poa.org 421
aeraf.gr 5456
oiggdf.po 98843

Code:

struct filedata
{
    char fname[50];
    int fsize;
};

int main()
{
    char line[60];
    int i=0;
    int numberoffiles=0;
    int lines=0;
    int ch=0;

    FILE *fp = fopen("mytext.txt","r");
    while ((ch = fgetc(fp)) != EOF)
    {
            if (ch == '\n')
                lines++;
    }

    struct filedata file[lines];
    numberoffiles=lines + 1;

    if(fp == (FILE*)NULL)
    {
        fprintf(stderr,"Cannot Open File\n");
        exit (-1);
    }
    else
    {
        while (fgets(line,60,fp)!=NULL)
        {
            sscanf(line,"%s %d",file[i].fname,&file[i].fsize);
            i++;
        }
    }
}
هل كانت مفيدة؟

المحلول

Your loop that counts the number of lines reads the entire file so that the current position is at the end of the file when you begin your second loop. Consider using rewind() before your second loop to move back to the start of the file.

Also, your test to see if fp is NULL should go right after the open() call. Otherwise, your code that reads the number of lines will fail.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top