The initial value of the file pointer position returned by ftell () in append mode

I watched SO post fseek does not work when the file is opened in "a" (append) , and I have doubts about the initial value of the file pointer returned by ftell () when we open the file in "a" mode. I tried under the code with the file1.txt file containing the "Hello welcome" data and printed the position of the pointer in different places. Ftell () will initially return position 0. After adding ftell () will return the last position. If we do fseek (), the file pointer will change, in which case I will return to 0 position. In add mode, we cannot read data. Why is the pointer in its original position? Also is there any use of fseek in add mode?

#include<stdio.h>
#include <string.h>
#include <errno.h>

#define MAX_BUF_SIZE 50

void readString(char* buffer,int maxSize)
{
    fgets(buffer,maxSize,stdin);
    // Note that if data is empty, strtok does not work. Use the other method instead.
    strtok(buffer,"\n");
}

extern int errno;

int main()
{
    FILE *fp1;
    char data[50];
    fp1=fopen("file1.txt","a");
    if(fp1==NULL)
    {
        // Print the error message
        fprintf(stderr,"%s\n",strerror(errno));
    }
    printf("Initial File pointer position in \"a\" mode = %ld\n",ftell(fp1));

    /* Initial file pointer position is 0 even in append mode
    As soon as data is write, FP points to the end.*/

    // Write some data at the end of the file only
    printf("\nEnter some data to be written to the file\n");
    readString(data,MAX_BUF_SIZE);
    // The data will be appended
    fputs(data,fp1);

    // File pointer points to the end after write operation
    printf("File pointer position after write operation in append mode = %ld\n",ftell(fp1));

    fseek(fp1,0,SEEK_SET);
    printf("File pointer position after fseek in append mode = %ld\n",ftell(fp1));

    return(0);
}
+4
source share
2 answers

You are asking

0 ?

, , , , . :

(, , ), , ( ) , , .

(C2011, 7.21.3/1)

, , . , ( , , "a +" ); , . , , , ( fseek().

fseek ?

, . , , , , , , . , . , ( , ), , - , fseek() -.

, fseek() , .

+2

0 ?

, -, . C, , .

fseek ?

, , fseek() . Per 7.21.5.3 fopen, 6 C:

('a' mode) , , fseek....

, 7, / "a+", fseek() :

('+' mode), , ....

, fseek() /, - , .

+1

Source: https://habr.com/ru/post/1688023/


All Articles