C/File/File Pointer

Материал из C\C++ эксперт
Версия от 13:22, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Reposition file pointer to a saved location: how to use fsetpos

<source lang="cpp">

  1. 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;

}

      </source>


Reset file position indicator to start of the file

<source lang="cpp">

  1. include <stdio.h>
  2. include <stdlib.h>
  3. 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;

}

      </source>


Return the current position in a stream: how to use ftell

<source lang="cpp">

  1. 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;

}


      </source>


Set the file pointer to the beginning of a stream: how to use rewind

<source lang="cpp">

  1. 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;

}

      </source>