Fputs
Int fputs (const char * STR, file * stream );
Write string to stream
Writes the string pointedStrToStream.
The function begins copying from the address specified (Str) Until it reaches the terminating null character ('/0'). This final null-character is not copied to the stream.
Parameters
-
Str
-
An array containing the null-terminated sequence of characters to be written.
-
Stream
-
Pointer to a file object that identifies the stream where the string is to be written.
Return Value
On success, a non-negative value is returned.
On error, the function returns EOF.
Example
#include <stdio.h> int main () { FILE * pFile; char sentence [256]; printf ("Enter sentence to append: "); fgets (sentence,255,stdin); pFile = fopen ("mylog.txt","a"); fputs (sentence,pFile); fclose (pFile); return 0; } |
This program allows to append a line to a file called mylog.txt each time it is run.
fgets
char * fgets ( char * str, int num, FILE * stream ); |
<cstdio> |
Get string from stream
Reads characters fromStreamAnd stores them as a C stringStrUntil (Num-1) characters have been read or either a newline or a end-of-file is reached, whichever comes first.
A newline character makesFgetsStop reading, but it is considered a valid character and therefore it is supported in the string copiedStr.
A null character is automatically appended inStrAfter the characters read to signal the end of the C string.
Parameters
-
Str
-
Pointer to an array CharS where the string read is stored.
-
Num
-
Maximum number of characters to be read (including the final null-character). Usually, the length of the array passed
StrIs used.
-
Stream
-
Pointer to a file object that identifies the stream where characters are read from.
To read from the standard input, StdinCan be used for this parameter.
Return Value
On success, the function returns the sameStrParameter.
If the end-of-file is encountered and no characters have been read, the contentsStrRemain unchanged and a null pointer is returned.
If an error occurs, a null pointer is returned.
Use either ferror or feof to check whether an error happened or the end-of-file was reached.
Example
#include <stdio.h> int main() { FILE * pFile; char mystring [100]; pFile = fopen ("myfile.txt" , "r"); if (pFile == NULL) perror ("Error opening file"); else { fgets (mystring , 100 , pFile); puts (mystring); fclose (pFile); } return 0; } |
This example reads the first lineMyfile.txtOr the first 100 characters, whichever comes first, and prints them on the screen.