Thursday, August 25, 2016

fgets() .. sscanf()


fgets()

char * fgets(char * str, int num, FILE * stream);
Get string from stream
Reads characters from stream and stores them as a C-string into str until(num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first...

A newline character makes fgets() stop reading, but it is considered a valid character by the function and included in the string copied to str...

A terminating null character is automatically appended after the characters copied to str...

NOTICE that fgets() is quite different from get(): NOT ONLY fgets() accepts a stream argument, BUT ALSO allows to specify the maximum size of str and includes in the string any ending newline character..

Parameters
str    Pointer to an array of chars where the string read is copied....
num  Maximum number of characters to be copied into str (including the terminating null-character)..

stream   Pointer to a FILE object that identifies an input stream..stdin can be used as argument to read from the standard input..

Return Values:
On success, the function returns str.
If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by strmay have changed).


//...char * sFile = "shader.vert";FILE * streamFile = fopen(sFile, "rt");if (NULL == streamFile ) return ;std::vector<std::string> sLines;char sLine[256] = {0};while (fgets(sLine, 256, streamFile ))    sLines.push_back(sLine);fclose(streamFile);streamFile = NULL;//...



sscanf()

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   int day, year;
   char weekday[20], month[20], dtm[100];

   strcpy( dtm, "Saturday March 25 1989" );
   sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

   printf("%s %d, %d = %s\n", month, day, year, weekday );
    
   return(0);
}

No comments:

Post a Comment