Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does fgets internally works?

Tags:

c

string

gcc

Well it is a basic question but I seem confused enough.

#include<stdio.h>
int main()
{
char a[100];
printf("Enter a string\n");
scanf("%s",a);
}

Basically the above is what I want to achieve. If I enter a string

James Bond

then I want that to be stored in array a. But the problem is because of presence of a blank space in between only James word is stored. So how can I solve this one.

UPDATE
After the replies given below I understand fgets() would be a better choice. I want to know internal working of fgets as why is it able to store the string with space where as scanf is not able to do the same.

like image 324
Registered User Avatar asked Jun 22 '11 07:06

Registered User


People also ask

Does fgets return anything?

RETURN VALUE Upon successful completion, fgets() returns s. If the stream is at end-of-file, the end-of-file indicator for the stream is set and fgets() returns a null pointer. If a read error occurs, the error indicator for the stream is set, fgets() returns a null pointer and sets errno to indicate the error.

Does fgets read line by line?

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

Is fgets safer than Scanf?

fgets is likely going to be the better choice. You can then use sscanf() to evaluate it. For numeric types, scanf() does not need to do bounds checking. For string types, you can tell scanf() to do boundary checking.

Can fgets read from file?

(Read String from File) In the C Programming Language, the fgets function reads characters from the stream pointed to by stream. The fgets function will stop reading when n-1 characters are read, the first new-line character is encountered in s, or at the end-of-file, whichever comes first.


1 Answers

Is this what you need?

  • freeBSD: http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/stdio/fgets.c?rev=1.14.14.1;content-type=text%2Fplain
  • open implementation: https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=7425&lngWId=3
  • OWP(dead) http://www.koders.com/c/fid042417FA231704B84308A66E1B82EADEDAB22051.aspx
  • ReactOS http://www.koders.com/c/fidEB3507945463053CEFCD518EA0CDFF9EB78E24C9.aspx?s=fgets.c#L1

All implementations scans the input file(or stream) until it reaches \n or EOF, or the maxSize param is hit...

like image 127
Quamis Avatar answered Sep 30 '22 03:09

Quamis