You are on page 1of 24

fopen

FILE * fopen ( const char * filename, const char * mode );


Open file

function

<cstdio>

Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE object whose pointer is returned. The operations that are allowed on the stream and how these are performed are defined by the mode parameter. The running environment supports at least FOPEN_MAX files open simultaneously; FOPEN_MAX is a macro constant defined in <cstdio>.

Parameters

filename C string containing the name of the file to be opened. This paramenter must follow the file name specifications of the running environment and can include a path if the system supports it. mode C string containing a file access modes. It can be: "r" Open a file for reading. The file must exist. Create an empty file for writing. If a file with the same name already exists its "w" content is erased and the file is treated as a new empty file. Append to a file. Writing operations append data at the end of the file. The file "a" is created if it does not exist. "r+" Open a file for update both reading and writing. The file must exist. Create an empty file for both reading and writing. If a file with the same name "w+" already exists its content is erased and the file is treated as a new empty file. Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can "a+" reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist. With the mode specifiers above the file is open as a text file. In order to open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string (thus making the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+"). Additional characters may follow the sequence, although they should have no effect. For example, "t" is sometimes appended to make explicit the file is a text file. In the case of text files, depending on the environment where the application runs, some special character conversion may occur in input/output operations to adapt them to a system-specific text file format. In many environments, such as most UNIX-based systems, it makes no difference to open a file as a text file or a binary file; Both are treated exactly the same way, but differentiation is recommended for a better portability. For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

Return Value
If the file has been succesfully opened the function will return a pointer to a FILE object that is used to identify the stream on all further operations involving it. Otherwise, a null pointer is returned.

Example

1 /* fopen example */ 2 #include <stdio.h> 3 int main () 4{ 5 FILE * pFile; 6 pFile = fopen ("myfile.txt","w"); 7 if (pFile!=NULL) 8 { 9 fputs ("fopen example",pFile); 10 fclose (pFile); 11 } 12 return 0; 13 }

fclose
<cstdio> int fclose ( FILE * stream );
Close file Closes the file associated with the stream and disassociates it. All internal buffers associated with the stream are flushed: the content of any unwritten buffer is written and the content of any unread buffer is discarded. Even if the call fails, the stream passed as parameter will no longer be associated with the file. function

Parameters
stream Pointer to a FILE object that specifies the stream to be closed.

Return Value

If the stream is successfully closed, a zero value is returned. On failure, EOF is returned.

Example
1 /* fclose example */ 2 #include <stdio.h> 3 int main () 4{ 5 FILE * pFile; 6 pFile = fopen ("myfile.txt","wt"); 7 fprintf (pFile, "fclose example"); 8 fclose (pFile); 9 return 0; 10 }

fwrite
<cstdio> size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
Write block of data to stream Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream. The postion indicator of the stream is advanced by the total number of bytes written. The total amount of bytes written is (size * count). function

Parameters
ptr size count stream Pointer to the array of elements to be written. Size in bytes of each element to be written. Number of elements, each one with a size of size bytes. Pointer to a FILE object that specifies an output stream.

Return Value

The total number of elements successfully written is returned as a size_t object, which is an integral data type. If this number differs from the count parameter, it indicates an error.

Example
1 /* fwrite example : write buffer */ 2 #include <stdio.h> 3 4 int main () 5{ 6 FILE * pFile; 7 char buffer[] = { 'x' , 'y' , 'z' }; 8 pFile = fopen ( "myfile.bin" , "wb" ); 9 fwrite (buffer , 1 , sizeof(buffer) , pFile ); 10 fclose (pFile); 11 return 0; 12 }

fread

function

<cstdio> size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
Read block of data from stream Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr. The postion indicator of the stream is advanced by the total amount of bytes read. The total amount of bytes read if successful is (size * count).

Parameters
ptr size count stream Pointer to a block of memory with a minimum size of (size*count) bytes. Size in bytes of each element to be read. Number of elements, each one with a size of size bytes. Pointer to a FILE object that specifies an input stream.

Return Value

The total number of elements successfully read is returned as a size_t object, which is an integral data type. If this number differs from the count parameter, either an error occured or the End Of File was reached. You can use either ferror or feof to check whether an error happened or the End-of-File was reached.

Example
1 /* fread example: read a complete file */ 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 int main () { 6 FILE * pFile; 7 long lSize; 8 char * buffer; 9 size_t result; 10 11 pFile = fopen ( "myfile.bin" , "rb" ); 12 if (pFile==NULL) {fputs ("File error",stderr); exit (1);} 13 14 // obtain file size: 15 fseek (pFile , 0 , SEEK_END); 16 lSize = ftell (pFile); 17 rewind (pFile); 18 19 // allocate memory to contain the whole file: 20 buffer = (char*) malloc (sizeof(char)*lSize); 21 if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);} 22 23 // copy the file into the buffer: 24 result = fread (buffer,1,lSize,pFile); 25 if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

26 27 28 29 30 31 32 33 }

/* the whole file is now loaded in the memory buffer. */ // terminate fclose (pFile); free (buffer); return 0;

This code loads myfile.bin into a dynamically allocated memory buffer, which can be used to manipulate the content of a file as an array

fprintf
<cstdio> int fprintf ( FILE * stream, const char * format, ... );
Write formatted output to stream Writes to the specified stream a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format. function

Parameters
stream format Pointer to a FILE object that identifies the stream. C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. The number of arguments following the format parameters should at least be as much as the number of format tags. The format tags follow this prototype:

%[flags][width][.precision][length]specifier
Where specifier is the most significant one and defines the type and the interpretation of the value of the coresponding argument: specifie Output Example r c a Character 392 d or i Signed decimal integer

e E f g G o s u x X p n %

Scientific notation (mantise/exponent) using e character Scientific notation (mantise/exponent) using E character Decimal floating point Use the shorter of %e or %f Use the shorter of %E or %f Signed octal String of characters Unsigned decimal integer Unsigned hexadecimal integer Unsigned hexadecimal integer (capital letters) Pointer address Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored. A % followed by another % character will write % to the stream.

3.9265e+2 3.9265E+2 392.65 392.65 392.65 610 sample 7235 7fa 7FA B800:0000

The tag can also contain flags, width, .precision and modifiers sub-specifiers, which are optional and follow these specifications: flags description Left-justify within the given field width; Right justification is the default (see width sub-specifier). Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(space If no sign is going to be written, a blank space is inserted before the value. ) Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point # even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed. Left-pads the number with zeroes (0) instead of spaces, where padding is 0 specified (see width sub-specifier). description Minimum number of characters to be printed. If the value to be printed is (number shorter than this number, the result is padded with blank spaces. The value ) is not truncated even if the result is larger. The width is not specified in the format string, but as an additional integer * value argument preceding the argument that has to be formatted. . precision description For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after de decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed. The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. description The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X). The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers cand s. The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G). width

.number

.*
lengt h

h l L

additional arguments Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in theformat parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value.

Return Value
On success, the total number of characters written is returned. On failure, a negative number is returned.

Example
1 /* fprintf example */ 2 #include <stdio.h> 3 4 int main () 5{ 6 FILE * pFile; 7 int n; 8 char name [100]; 9 10 pFile = fopen ("myfile.txt","w"); 11 for (n=0 ; n<3 ; n++) 12 { 13 puts ("please, enter a name: "); 14 gets (name); 15 fprintf (pFile, "Name %d [%-10.10s]\n",n,name); 16 } 17 fclose (pFile); 18 19 return 0; 20 }
This example prompts 3 times the user for a name and then writes them to myfile.txt each one in a line with a fixed length (a total of 19 characters + newline). Two format tags are used: %d : Signed decimal integer %-10.10s : left aligned (-), minimum of ten characters (10), maximum of ten characters (.10), String (s) . Assuming that we have entered John, Jean-Francois and Yoko as the 3 names, myfile.txt would contain: myfile.txt

Name 1 [John ] Name 2 [Jean-Franc] Name 3 [Yoko ]

fputs
int fputs ( const char * str, FILE * stream );
Write string to stream

function

<cstdio>

Writes the string pointed by str to the stream. 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 stream An array containing the null-terminated sequence of characters to be written. 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
1 /* fputs example */ 2 #include <stdio.h> 3 4 int main () 5{ 6 FILE * pFile; 7 char sentence [256]; 8 9 printf ("Enter sentence to append: "); 10 fgets (sentence,255,stdin); 11 pFile = fopen ("mylog.txt","a"); 12 fputs (sentence,pFile); 13 fclose (pFile); 14 return 0; 15 }

This program allows to append a line to a file called mylog.txt each time it is run.

fscanf
<cstdio> int fscanf ( FILE * stream, const char * format, ... );
Read formatted data from stream Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string. function

Parameters
stream format Pointer to a FILE object that identifies the stream to read data from. C string that contains one or more of the following items:

Whitespace character: the function will read and ignore any whitespace characters (this includes blank spaces and the newline and tab characters) which are encountered before the next non-whitespace character. This includes any quantity of whitespace characters, or none. Non-whitespace character, except percentage signs (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this nonwhitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread. Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored in the locations pointed by the additional arguments. A format specifier follows this prototype: [=%[*][width][modifiers]type=] where: An optional starting asterisk indicates that the data is to be read from the stream but ignored, i.e. it is not stored in the corresponding argument. Specifies the maximum number of characters to be read in the width current reading operation Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data pointed by the corresponding additional argument: modifier h : short int (for d, i and n), or unsigned short s int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g) * type A character specifying the type of data to be read and how it is expected to be read. See next table.

fscanf type specifiers: type Qualifying Input Type of argument

Single character: Reads the next character. If a width different from 1 is specified, the function char * reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end. Decimal integer: Number optionally preceeded with int * a + or - sign.

Floating point: Decimal number containing a decimal point, optionally preceeded by a + or - sign and e,E,f,g, float * optionally folowed by the e or Echaracter and a G decimal number. Two examples of valid entries are -732.103 and 7.12e4 o int * Octal integer. String of characters. This will read subsequent characters until a whitespace is found (whitespace s char * characters are considered to be blank, newline and tab).

u x,X

Unsigned decimal integer. Hexadecimal integer.

unsigned int * int *

additional arguments The function expects a sequence of references as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order. For each format specifier in the format string that retrieves data, an additional argument should be specified. These arguments are expected to be references (pointers): if you want to store the result of a fscanf operation on a regular variable you should precede its identifier with thereference operator, i.e. an ampersand sign (&), like in:

int n; fscanf (stream,"%d",&n);

Return Value

On success, the function returns the number of items succesfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned.

Example
1 /* fscanf example */ 2 #include <stdio.h> 3 4 int main () 5{ 6 char str [80]; 7 float f; 8 FILE * pFile; 9 10 pFile = fopen ("myfile.txt","w+"); 11 fprintf (pFile, "%f %s", 3.1416, "PI"); 12 rewind (pFile); 13 fscanf (pFile, "%f", &f); 14 fscanf (pFile, "%s", str); 15 fclose (pFile);

16 printf ("I have read: %f and %s \n",f,str); 17 return 0; 18 }

This sample code creates a file called myfile.txt and writes a float number and a string to it. Then, the stream is rewinded and both values are read with fscanf. It finally produces an output similar to:

I have read: 3.141600 and PI

fputc
<cstdio> int fputc ( int character, FILE * stream );
Write character to stream Writes a character to the stream and advances the position indicator. The character is written at the current position of the stream as indicated by the internal position indicator, which is then advanced one character. function

Parameters

character Character to be written. The character is passed as its int promotion. stream Pointer to a FILE object that identifies the stream where the character is to be written.

Return Value
If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set (see ferror).

Example
1 /* fputc example: alphabet writer */ 2 #include <stdio.h> 3 4 int main () 5{ 6 FILE * pFile; 7 char c; 8 9 pFile = fopen ("alphabet.txt","w"); 10 if (pFile!=NULL) 11 { 12 for (c = 'A' ; c <= 'Z' ; c++) 13 { 14 fputc ( (int) c , pFile ); 15 } 16 fclose (pFile); 17 } 18 return 0; 19 }

This program creates a file called alphabet.txt and writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to it.

puts
<cstdio> int fputs ( const char * str, FILE * stream );
Write string to stream Writes the string pointed by str to the stream. 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. function

Parameters
str stream An array containing the null-terminated sequence of characters to be written. 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
1 /* fputs example */ 2 #include <stdio.h> 3 4 int main () 5{ 6 FILE * pFile; 7 char sentence [256]; 8 9 printf ("Enter sentence to append: "); 10 fgets (sentence,255,stdin); 11 pFile = fopen ("mylog.txt","a"); 12 fputs (sentence,pFile); 13 fclose (pFile); 14 return 0; 15 }

This program allows to append a line to a file called mylog.txt each time it is run.

fgetc
<cstdio> int fgetc ( FILE * stream );
Get character from stream Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character. fgetc and getc are equivalent, except that the latter one may be implemented as a macro. function

Parameters
stream Pointer to a FILE object that identifies the stream on which the operation is to be performed.

Return Value

The character read is returned as an int value. If the End-of-File is reached or a reading error happens, the function returns EOF and the corresponding error or eof indicator is set. You can use either ferror or feof to determine whether an error happened or the End-Of-File was reached.

Example
1 /* fgetc example: money counter */ 2 #include <stdio.h> 3 int main () 4{ 5 FILE * pFile; 6 int c; 7 int n = 0; 8 pFile=fopen ("myfile.txt","r"); 9 if (pFile==NULL) perror ("Error opening file"); 10 else 11 { 12 do { 13 c = fgetc (pFile); 14 if (c == '$') n++; 15 } while (c != EOF); 16 fclose (pFile); 17 printf ("The file contains %d dollar sign characters ($).\n",n); 18 } 19 return 0; 20 }

This program reads an existing file called myfile.txt character by character and uses the n variable to count how many dollar characters ($) does the file contain.

fgets
<cstdio> 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 a the End-of-File is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters read to signal the end of the C string. function

Parameters
str num stream Pointer to an array of chars where the string read is stored. Maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used. Pointer to a FILE object that identifies the stream where characters are read from. To read from the standard input, stdin can be used for this parameter.

Return Value
On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain 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
1 /* fgets example */ 2 #include <stdio.h> 3 4 int main() 5{ 6 FILE * pFile; 7 char mystring [100]; 8 9 pFile = fopen ("myfile.txt" , "r"); 10 if (pFile == NULL) perror ("Error opening file"); 11 else { 12 fgets (mystring , 100 , pFile); 13 puts (mystring); 14 fclose (pFile); 15 } 16 return 0; 17 }

This example reads the first line of myfile.txt or the first 100 characters, whichever comes first, and prints them on the screen.

feof
<cstdio> int feof ( FILE * stream );
Check End-of-File indicator Checks whether the End-of-File indicator associated with stream is set, returning a value different from zero if it is. This indicator is generally set by a previous operation on the stream that reached the End-ofFile. Further operations on the stream once the End-of-File has been reached will fail until either rewind, fseek or fsetpos is successfully called to set the position indicator to a new value. function

Parameters
stream Pointer to a FILE object that identifies the stream.

Return Value

A non-zero value is returned in the case that the End-of-File indicator associated with the stream is set. Otherwise, a zero value is returned.

Example
1 /* feof example: byte counter */ 2 #include <stdio.h> 3 int main () 4{ 5 FILE * pFile; 6 long n = 0; 7 pFile = fopen ("myfile.txt","rb"); 8 if (pFile==NULL) perror ("Error opening file"); 9 else 10 { 11 while (!feof(pFile)) { 12 fgetc (pFile); 13 n++; 14 } 15 fclose (pFile); 16 printf ("Total number of bytes: %d\n", n-1); 17 } 18 return 0; 19 }

This code opens the file called myfile.txt, and counts the number of characters that it contains by reading all of them one by one. Finaly the total amount of bytes is printed out.

fflush
<cstdio> int fflush ( FILE * stream );
Flush stream If the given stream was open for writing and the last i/o operation was an output operation, any unwritten data in the output buffer is written to the file. If it was open for reading and the last operation was an input operation, the behavior depends on the specific library implementation. In some implementations this causes the input buffer to be cleared, but this is not standard behavior. If the argument is a null pointer, all open files are flushed. The stream remains open after this call. When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed. function

Parameters
stream Pointer to a FILE object that specifies a buffered stream.

Return Value

A zero value indicates success. If an error occurs, EOF is returned and the error indicator is set (see feof).

Example

In files open for update (i.e., open for both reading and writting), the stream shall be flushed after an output operation before performing an input operation. This can be done either by repositioning (fseek, fsetpos, rewind) or by calling explicitly fflush, like in this example:

1 /* fflush example */ 2 #include <stdio.h> 3 char mybuffer[80]; 4 int main() 5{ 6 FILE * pFile; 7 pFile = fopen ("example.txt","r+"); 8 if (pFile == NULL) perror ("Error opening file"); 9 else { 10 fputs ("test",pFile); 11 fflush (pFile); // flushing or repositioning required 12 fgets (mybuffer,80,pFile); 13 puts (mybuffer); 14 fclose (pFile); 15 return 0; 16 } 17 }

fgetpos
int fgetpos ( FILE * stream, fpos_t * position );
Get current position in stream

function

<cstdio>

Gets the information needed to uniquely identify the current value of the stream's position indicator and stores it in the location pointed by position. The parameter position should point to an already allocated object of the type fpos_t, which is only intended to be used as a paremeter in future calls to fsetpos. To retrieve the value of the internal file position indicator as an integer value, use ftell function instead.

Parameters
stream position Pointer to a FILE object that identifies the stream. Pointer to a fpos_t object.

Return Value Example

The function return a zero value on success, and a non-zero value in case of error.

1 /* fgetpos example */ 2 #include <stdio.h> 3 int main () 4{ 5 FILE * pFile; 6 int c; 7 int n; 8 fpos_t pos; 9 10 pFile = fopen ("myfile.txt","r"); 11 if (pFile==NULL) perror ("Error opening file"); 12 else 13 { 14 c = fgetc (pFile); 15 printf ("1st character is %c\n",c); 16 fgetpos (pFile,&pos); 17 for (n=0;n<3;n++) 18 { 19 fsetpos (pFile,&pos); 20 c = fgetc (pFile); 21 printf ("2nd character is %c\n",c); 22 } 23 fclose (pFile); 24 } 25 return 0; 26 }
Output: 1st character is A 2nd character is B 2nd character is B

2nd character is B The example opens myfile.txt, reads the first character once and then it reads 3 times the same second character.

fseek
<cstdio> int fseek ( FILE * stream, long int offset, int origin );
Reposition stream position indicator Sets the position indicator associated with the stream to a new position defined by adding offset to a reference position specified by origin. The End-of-File internal indicator of the stream is cleared after a call to this function, and all effects from previous calls to ungetc are dropped. When using fseek on text files with offset values other than zero or values retrieved with ftell, bear in mind that on some platforms some format transformations occur with text files which can lead to unexpected repositioning. On streams open for update (read+write), a call to fseek allows to switch between reading and writing. function

Parameters
stream offset origin Pointer to a FILE object that identifies the stream. Number of bytes to offset from origin. Position from where offset is added. It is specified by one of the following constants defined in <cstdio>: SEEK_SET Beginning of file SEEK_CUR Current position of the file pointer SEEK_END End of file

Return Value

If successful, the function returns a zero value. Otherwise, it returns nonzero value.

Example
1 /* fseek example */ 2 #include <stdio.h> 3 4 int main () 5{ 6 FILE * pFile; 7 pFile = fopen ( "example.txt" , "w" ); 8 fputs ( "This is an apple." , pFile ); 9 fseek ( pFile , 9 , SEEK_SET ); 10 fputs ( " sam" , pFile ); 11 fclose ( pFile ); 12 return 0; 13 }

After this code is successfully executed, the file example.txt contains:

This is a sample.

fsetpos
<cstdio> int fsetpos ( FILE * stream, const fpos_t * pos );
Set position indicator of stream Changes the internal file position indicator associated with stream to a new position. The position parameter is a pointer to an fpos_t object whose value shall have been previously obtained with a call to fgetpos. The End-of-File internal indicator of the stream is cleared after a call to this function, and all effects from previous calls to ungetc are dropped. On streams open for update (read+write), a call to fsetpos allows to switch between reading and writing. function

Parameters
stream position Pointer to a FILE object that identifies the stream. Pointer to a fpos_t object containing a position previously obtained with fgetpos.

Return Value

If successful, the function returns a zero value. Otherwise, it returns a nonzero value and sets the global variable errno to a positive value, which can be interpreted with perror.

Example
1 /* fsetpos example */ 2 #include <stdio.h> 3 4 int main () 5{ 6 FILE * pFile; 7 fpos_t position; 8 9 pFile = fopen ("myfile.txt","w"); 10 fgetpos (pFile, &position); 11 fputs ("That is a sample",pFile); 12 fsetpos (pFile, &position); 13 fputs ("This",pFile); 14 fclose (pFile); 15 return 0; 16 }

After this code is successfully executed, a file called myfile.txt will contain:

This is a sample

rewind
<cstdio> void rewind ( FILE * stream );
Set position indicator to the beginning Sets the position indicator associated with stream to the beginning of the file. A call to rewind is equivalent to: function

fseek ( stream , 0L , SEEK_SET ); except that, unlike fseek, rewind clears the error indicator. On streams open for update (read+write), a call to rewind allows to switch between reading
and writing.

Parameters
stream Pointer to a FILE object that identifies the stream.

Return Value
none

Example
1 /* rewind example */ 2 #include <stdio.h> 3 4 int main () 5{ 6 int n; 7 FILE * pFile; 8 char buffer [27]; 9 10 pFile = fopen ("myfile.txt","w+"); 11 for ( n='A' ; n<='Z' ; n++) 12 fputc ( n, pFile); 13 rewind (pFile); 14 fread (buffer,1,26,pFile); 15 fclose (pFile); 16 buffer[26]='\0'; 17 puts (buffer); 18 return 0; 19 }

A file called myfile.txt is created for reading and writing and filled with the alphabet. The file is then rewinded, read and its content is stored in a buffer, that then is written to the standard output:

You might also like