Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fscanf return value

Tags:

c

scanf

What does fscanf return when it reads data in the file. For example,

int number1, number2, number3, number4, c;

c = fscanf (spFile, "%d", &number1);
//c will be 1 in this case.

c = fscanf (spFile, "%d %d %d %d", &number1, &number1, &number3, &number4);
//in this case, c will return 4.

I just want to know why it returns such values depending on the number of arguments.

like image 905
slow Avatar asked Mar 10 '13 02:03

slow


People also ask

What does fscanf return at EOF?

fscanf returns EOF if end of file (or an input error) occurs before any values are stored. If values are stored, it returns the number of items stored; that is, the number of times a value is assigned with one of the fscanf argument pointers.

How does fscanf work in C?

fscanf Function in CThis function is used to read the formatted input from the given stream in the C language. Syntax: int fscanf(FILE *ptr, const char *format, ...) fscanf reads from a file pointed by the FILE pointer (ptr), instead of reading from the input stream.

What is the return value of sscanf?

Return Value The sscanf() function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned. The return value is EOF when the end of the string is encountered before anything is converted.


2 Answers

From the manpage for the Xscanf family of functions:

Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned, and errno shall be set to indicate the error

So your first call to fscanf returns 1 because one input item (&number1) was successfully matched with the format specifier %d. Your second call to fscanf returns 4 because all 4 arguments were matched.

like image 69
Charles Salvia Avatar answered Oct 25 '22 02:10

Charles Salvia


I quote from cplusplus.com .

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

--EDIT--

If you are intention is to determine the number of bytes read to a string.

int bytes;
char str[80];
fscanf (stdin, "%s%n",str,&bytes);
printf("Number of bytes read = %d",bytes);
like image 30
Barath Ravikumar Avatar answered Oct 25 '22 02:10

Barath Ravikumar