fgets and sscanf

2019-09-08 05:37发布

This code is supposed to get integers from a file which is finput and sort it and gets the first integer in the file which is the number of integers to be sorted and the integers that follow are the integers to be sorted. I don't get how fgets and sscanf work together. Can someone explain how fgets and sscanf work in this code?

FILE *finput;
int *array_int, c1, no_elem;
char numlines[500];

fgets(numlines, 500, finput); 
array_int = (int *)malloc(sizeof(int)*no_elem);
if ((sscanf(numlines, "%d", &no_elem) == 1) &&  array_int!= NULL)
{
    for(c1=0; fgets(numlines, 500, finput) != NULL; )  
    {
        if (sscanf(numlines, "%d", &array_int[c1])==1) 
        {
            ++c1;
        }
    }
}

标签: c fgets scanf
1条回答
太酷不给撩
2楼-- · 2019-09-08 06:13

fgets gets a string (i.e. a line of text) from the file.

sscanf parses a string based on the format string. It is reverse to sprintf. the <x>printf and matching <x>scanf functions allow formatted output and input accordingly, with a standard format string. For example, "%d" means "signed integer value", and in context of <x>scanf it means "read it into the next parameter in the following list of parameters" (your array member in your case).

You can parse directly from the file using fscanf, but using fgets + sscanf instead allows for more flexibility and might be safer.

查看更多
登录 后发表回答