【问题标题】:extra spaces written in r+ mode以 r+ 模式写入的额外空格
【发布时间】:2018-05-13 21:59:25
【问题描述】:

在下面的代码中,如果我在寻找指向行后起始位置的文件指针后写入数据,则会附加额外的 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;
}

【问题讨论】:

  • 只是指出要避免这种用法,getchar 的返回类型是 int。您捕获的返回值在 char ch 中。
  • 无法复制。我在文件的开头和结尾都插入了“今天”。根本没有多余的空间。 BTW:在最后一次打印文件之前,如果你想打印整个文件,你应该添加一个fseek(fp1,0,SEEK_SET);
  • OT:永远不要使用gets
  • @4386427 你能告诉我你用的是什么编译器吗?我的朋友还说他在 MinGW 中没有遇到问题
  • OT:char ch; ==> int ch;

标签: c file tdm-gcc


【解决方案1】:

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

在更新模式 ('+') 下,可以同时执行输入和输出,但是如果没有对 fflush、fseek、fsetpos 或 rewind 的介入调用,则输出不能跟随输入,并且如果没有介入,输入不能跟随输出调用 fseek、fsetpos 或 rewind,除非输入操作遇到文件结尾。

读取和写入可能会被缓冲,但仍共享单个文件位置。在不提醒运行时 (fseek) 的情况下切换模式可能会弄乱缓冲。就像你注意到的那样!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2016-05-24
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    相关资源
    最近更新 更多