首页 > 解决方案 > extra spaces written in r+ mode

问题描述

In the code below, extra spcaes (may be around 300 space) are getting appended if I write data after seeking the file pointer to the start position after the line

fseek(fp1,0,SEEK_SET);

If I comment second fputs() function call, there is no issue. Also the inputted data is not getting appended at the end, instead only spaces are getting appended. I am unable to identify the problem.

I am using TDM-GCC-64 compiler.

For testing purpose, file1.txt had contents "Welcome to You All" at the beginning. Inputted data: "Today" Output after execution of the program: "Todayme to You All" followed by many spaces.

int main()
{
    FILE *fp1;
    char ch;
    char data[50];
    fp1=fopen("file1.txt", "r+");
    if(fp1==NULL)
    {
        printf("Error in Opening the file\n");
        return(0);
    }

    printf("Read and Write Mode. The data in the file is\n");
    while((ch=getc(fp1))!=EOF)
    {
        putc(ch,stdout);
    }
    // Write some data at the end of the file
    printf("\nEnter some data to be written to the file\n");
    gets(data);
    fseek(fp1,0,SEEK_END);
    fputs(data,fp1);
    fseek(fp1,0,SEEK_SET);
    fputs(data,fp1);
    printf("data in file after write operation is\n");
    while((ch=getc(fp1))!=EOF)
    {
        putc(ch,stdout);
    }
    fclose(fp1);
    return 0;
}

标签: cfiletdm-gcc

解决方案


You should check the fine print in the fopen documentation:

In update mode ('+'), both input and output may be performed, but output cannot be followed by input without an intervening call to fflush, fseek, fsetpos or rewind, and input cannot be followed by output without an intervening call to fseek, fsetpos or rewind, unless the input operation encountered end of file.

Reading and writing might be buffered, but still share a single file position. Switching modes without alerting the runtime (fseek) could mess up the buffering. Like you have noticed!


推荐阅读