简体   繁体   English

c++文件读/写无限循环,再次重写txt

[英]c++ file read/write infinite loop that rewrites the txt again

I'm trying to learn how to use file handling in C++.我正在尝试学习如何在 C++ 中使用文件处理。 I'd like to save and edit the contents of variables, however, there seems to be a problem with my logic because somehow the following program re writes the contents of the file infinitely.我想保存和编辑变量的内容,但是,我的逻辑似乎有问题,因为以下程序以某种方式无限地重写了文件的内容。

#include <stdio.h>
#include <iostream>

int main(int argc, char const *argv[])
{
    FILE *filePointer = fopen("text.txt", "r+");
    char currentChar;
    int loop = 0;
    currentChar = getc(filePointer);
    while (currentChar != EOF && loop < 100)
    {
        if (currentChar == '=')
        {
            fseek(filePointer, 1, 1);
            if (fputs("LOL", filePointer) == EOF)
            {
                return 2;
            }
            
        }
        
        std::cout << ftell(filePointer) << "Current Char: " << currentChar << std::endl;
        currentChar = getc(filePointer);
        
        loop++;
    }
    fclose(filePointer);
    return 0;
}

The code that the program reads is the following:程序读取的代码如下:

" hello = \n yay! " “你好=\n耶!”

This program exhibits undefined behavior.该程序表现出未定义的行为。 From C99 standard (which governs C standard library functions and is incorporated into the C++ standard by reference):从 C99 标准(管理 C 标准库函数并通过引用并入 C++ 标准):

7.19.5.3/6 When a file is opened with update mode ( '+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. 7.19.5.3/6当文件以更新模式打开时( '+'作为上述mode参数值列表中的第二个或第三个字符),输入和 output 都可以在关联的 stream 上执行。 However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function ( fseek , fsetpos , or rewind ), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function ( fseek , fsetpos , or rewind ), and input shall not be directly followed by output without an intervening call to a file positioning function,除非输入操作遇到文件结束。

You have output ( fputs ) immediately followed by input ( getc ) without an intervening fflush or a file positioning function.您有 output ( fputs ) 紧随其后的是输入 ( getc ),没有中间的fflush或文件定位 function。

Text is stored contiguously on disk, and just like arrays, if you want to insert it, you must move the original element back, otherwise the effect of the execution is an overlay文本是连续存储在磁盘上的,和arrays一样,如果要插入,必须把原来的元素往后移,否则执行的效果就是叠加

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM