<< Chapter < Page | Chapter >> Page > |
Output:
File opened successfully. Contents:
String: 111 222 3String: 33String: 444 555 6String: 66
String: 777 888 9String: 99Now closing file...
The main area of focus is the while loop - notice how I performed the check for the return of a NULL pointer. Remember that passing in char * variable, c as the first argument assigns the line read into c, which is printed off by printf. We specified a maximum number of characters to be 10 - we knew the number of characters per line in our text file is more than this, but we wanted to show that fgets reads 10 characters at a time in this case.
Notice how fgets returns when the newline character is reached - this would explain why 444 and 777 follow the word "String". Also, the tab character, \t, is treated as one character.
int fseek (FILE *fp, long int offset, int origin);
In the above prototype, there are two arguments:
Constant | Value | Meaning |
SEEK_SET | 0 | Beginning of file |
SEEK_CUR | 1 | Current position of the file pointer |
SEEK_END | 2 | End of file |
This function sets the position indicator associated with the fp to a new position defined by adding offset to a reference position specified by origin. The End-of-File internal indicator of the file is cleared after a call to this function.
Return Value: If successful, the function returns a zero value. Otherwise, it returns nonzero value.
#include<stdio.h>int main ()
{FILE * fp;
fp = fopen ( "myfile.txt" , "w" );fputs ( "This is an apple." , fp );
fseek ( fp , -8 , SEEK_END );fputs ( " sam" , fp );
fclose ( fp );return 0;
}
After this code is successfully executed, the file myfile.txt contains:
This is a sample.
#include<stdio.h>int main ()
{FILE * fp;
fp = fopen ( "myfile.txt" , "w" );fputs ( "This is an apple." , fp );
fseek ( fp , 9 , SEEK_SET );fputs ( " sam" , fp );
fclose ( fp );return 0;
}
After this code is successfully executed, the file myfile.txt contains:
This is a sample.
void rewind (FILE *fp);
This function sets the current position indicator associated with fp to the beginning of the file. A call to rewind is equivalent to:
fseek (fp, 0, 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.
#include<stdio.h>#include<conio.h>int main ()
{char str [80];int n;
FILE * fp;fp = fopen ("myfile.txt","w+");
for ( n='A' ; n<='Z' ; n++)
fputc ( n, fp);rewind (fp);
n=0;while (!feof(fp))
{str[n]= fgetc(fp);n++;
}fclose (fp);
printf ("I have read: %s \n",str);getch();
return 0;}
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:
Notification Switch
Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?