c - 以 r+ 模式写入的额外空格

标签 c file tdm-gcc

在下面的代码中,如果我在查找指向行后起始位置的文件指针后写入数据,则会附加额外的 spcaes(可能约为 300 个空格)

fseek(fp1,0,SEEK_SET);

如果我注释第二个 fputs() 函数调用,则没有问题。 此外,输入的数据不会附加在末尾,而是仅附加空格。 我无法确定问题所在。

我正在使用 TDM-GCC-64 编译器。

出于测试目的,file1.txt 的开头内容为“Welcome to You All”。 输入数据:“今天” 程序执行后的输出:“Todayme to You All”后跟许多空格。

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;
}

最佳答案

您应该检查 fopen 中的细则。文档:

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.

读取和写入可能会被缓冲,但仍然共享单个文件位置。在不提醒运行时 (fseek) 的情况下切换模式可能会扰乱缓冲。正如您所注意到的!

关于c - 以 r+ 模式写入的额外空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50314162/

相关文章:

java - java从mysql数据库读取docx文件

c - C 中的套接字和线程

c++ - 运行 OFX 插件

python - 重命名不同文件夹中同名的文件

c - 如何设置 OpenMP?

go - 如何在 cgo 中正确使用 64 位 TDM-GCC?

c++ - 在 Windows XP 和 CodeBlocks 上延迟加载 DWMAPI

c - 使用 glOrthof 时,我只看到一个十字

c - 在C中初始化一个结构表

eclipse - Eclipse IDE 中基于模式的文件选择和删除