Fgets and sscanf?

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

Up vote 0 down vote favorite share g+ share fb share tw.

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 numlines500; 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_intc1)==1) { ++c1; } } } c fgets sscanf link|improve this question edited Mar 25 at 8:33galymzhan1,378314 asked Mar 25 at 8:27John32.

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 printf and matching scanf functions allow formatted output and input accordingly, with a standard format string. For example, "%d" means "signed integer value", and in context of 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.

– galymzhan Mar 25 at 8:39 @galymzhan can't think of any off the top of my head. Why? – littleadv Mar 25 at 8:41 So fgets gets the integer and sscanf assigns that integer to array_int?

Am I right? Why is there a ==1 in sscanf? – John Mar 25 at 8:41 @John, did you read the first sentence in my answer?

How did you reach this conclusion? You're reading a text string, and then you parse the text string. These are two, distinct and unrelated actions.

There's a function that does them both at once, or you can do them separately. – littleadv Mar 25 at 8:43 @littleadv Just curious, I've been using fscanf directly most of the time. – galymzhan Mar 25 at 8:43.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions