C/File/File Pointer
Содержание
Reposition file pointer to a saved location: how to use fsetpos
#include <stdio.h>
int main ()
{
FILE * file;
fpos_t pos;
file = fopen ("my.txt", "w");
fgetpos(file, &pos);
fputs ("That is a line." ,file);
fsetpos (file, &pos);
fputs ("This", file);
fclose (file);
return 0;
}
Reset file position indicator to start of the file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char str[80];
FILE *fp;
if((fp = fopen("TEST", "w+"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
do {
printf("Enter a string (CR to quit):\n");
gets(str);
strcat(str, "\n"); /* add a newline */
fputs(str, fp);
} while(*str!="\n");
rewind(fp); /* reset file position indicator to
start of the file. */
while(!feof(fp)) {
fgets(str, 79, fp);
printf(str);
}
return 0;
}
Return the current position in a stream: how to use ftell
#include <stdio.h>
int main ()
{
FILE *file;
long size;
file = fopen ("my.txt","rb");
if (file == NULL)
perror ("Error reading my.txt.");
else {
fseek (file, 0, SEEK_END);
size = ftell(file);
fclose (file);
printf ("Size of my.txt is %ld bytes.\n",size);
}
return 0;
}
Set the file pointer to the beginning of a stream: how to use rewind
#include <stdio.h>
int main ()
{
int n;
FILE *file;
char buffer[27];
file = fopen ("my.txt", "w+");
for ( n="A" ; n<="Z" ; n++)
fputc ( n, file);
rewind ( file );
fread (buffer, 1, 26, file);
fclose ( file );
buffer[26] = "\0";
puts ( buffer );
return 0;
}