简体   繁体   English

更新C中的文本文件(可能吗?)

[英]updating text files in C(is it possible?)

Do any of you guys know if it's possible to update a text file(eg something.txt) in C? 你们是否知道是否可以在C中更新文本文件(例如something.txt)? I was expecting to find a function with similar syntax as update_txt(something.txt), but I haven't found anything while browsing the internet for the last 2 hours..... The thing is that I would like some data to be stored and displayed in real time in an already opened text file. 我原本希望找到一种语法与update_txt(something.txt)类似的函数,但是在过去2个小时的互联网浏览过程中我什么都没发现。....问题是我希望得到一些数据存储并实时显示在已打开的文本文件中。 I can store the data but I am unable to find a way to display it without manually closing the text file and then open it again... 我可以存储数据,但无法找到一种无需手动关闭文本文件然后再次打开的方法来显示它...

Do someone know how to solve this issue? 有人知道如何解决这个问题吗? Or do you have another way to solve it? 还是您有另一种解决方法? I have read something about transferring data to a new text document and then renaming it, but I am quite sure that this wouldn't solve my problem. 我已经读过一些有关将数据传输到新的文本文档然后重命名的内容,但是我确信这不会解决我的问题。 I have also read something about macros that could detect changes in the document and then somehow refresh it. 我还阅读了一些有关宏的内容,这些宏可以检测到文档中的更改,然后以某种方式刷新它。 I have never worked with macros and I have absolutely no idea of how they are implemented.... 我从未使用过宏,而且我完全不知道如何实现它们。

But please tell me if it is a fact that it is impossible to update an already opened text document? 但是请告诉我是否不可能更新已经打开的文本文档?

I am thankful for any suggestions or tutorials that you guys may provide! 感谢您提供的任何建议或教程! :) :)

That's outside the scope of C; 那超出了C的范围; it will require some system-specific filesystem monitoring mechanism. 它将需要一些特定于系统的文件系统监视机制。 For example, inotify offers this functionality 例如, inotify提供了此功能

First off, you can use the rewind() , fseek() , ftell() or fgetpos() and fsetpos() functions to locate the read pointer in a file. 首先,您可以使用rewind()fseek()ftell()fgetpos()fsetpos()函数在文件中定位读取指针。 If you record the start position where the updated record was written (the start offset) using ftell() or fgetpos() , you could jump back to that position later with fseek() or fsetpos() and read in the changed data. 如果使用ftell()fgetpos()记录写入更新记录的起始位置(起始偏移量),则可以稍后使用fseek()fsetpos()跳回到该位置并读入更改的数据。

The other gotcha lurking here is that in general, you can't simply 'update' a text file. 潜伏在这里的另一个陷阱是,通常,您不能简单地“更新”文本文件。 Specifically, if the replacement text is not the same length as the original text, you have problems. 具体来说,如果替换文本的长度与原始文本的长度不同,则可能会出现问题。 You either need to expand or contract the file. 您需要扩展或收缩文件。 This is normally done by making a copy with the desired edit in the correct location, and then copying or moving the modified copy of the file over the original file. 通常通过在正确的位置进行具有所需编辑的副本,然后将文件的修改后的副本复制或移动到原始文件上来完成此操作。

Detecting when some other process modifies the file is harder still. 检测其他进程何时修改文件仍然更加困难。 There are different mechanisms in different operating systems. 不同的操作系统中有不同的机制。 For Linux, it is the inotify system, for example. 例如,对于Linux,它是inotify系统。

Based upon your statement that you 'can't display it without manually closing the text file and open it again', it may be a buffer issue. 根据您的陈述,即“如果不手动关闭文本文件然后再次打开它,就无法显示它”,这可能是缓冲区问题。 When using the C standard library calls ( fopen , fread , fwrite , fclose , etc ...) the data you write may be buffered in user-space until the buffer is full or the file is closed. 使用C标准库调用( fopenfreadfwritefclose等)时,您写入的数据可能会在用户空间中缓冲,直到缓冲区已满或文件关闭。

To force the C library to flush the buffer, use the fflush(fp) call where fp is your file pointer. 要强制C库刷新缓冲区,请使用fflush(fp)调用,其中fp是您的文件指针。

Regarding: But please tell me if it is a fact that it is impossible to update an already opened text document? 关于: 但是请告诉我是否不可能更新已经打开的文本文档? Yes, it is not possible , unless you own the handle to the file (ie FILE *fp = fopen("someFilePath", "w+");) 是的,这是不可能的除非您拥有文件的句柄 (即FILE * fp = fopen(“ someFilePath”,“ w +”);)

Regarding: if it's possible to update a text file(eg something.txt) in C? 关于: 是否可以在C中更新文本文件(例如something.txt)?
Yes . 是的 If you know the location of the file, (someFileLocation, eg. "c:\\dev\\somefile.txt"), then open it and write to it. 如果您知道文件的位置(someFileLocation,例如“ c:\\ dev \\ somefile.txt”),则将其打开并写入。

A simple function that uses FILE *fp = fopen(someFileLocation, "w+"); 一个简单的函数,使用FILE *fp = fopen(someFileLocation, "w+"); (open existing file for append) and fclose(fp); (打开现有文件进行追加)和fclose(fp); will do that: Here is an example that I use for logging: 将做到这一点:这是我用于记录日志的示例:

(Note, you will have to comment out, or create the other functions this one refers to, but the general concept is shown) (请注意,您必须注释掉,或创建该功能所引用的其他功能,但会显示一般概念)

int WriteToLog(char* str)
{
    FILE* log;
    char *tmStr;
    ssize_t size;
    char pn[MAX_PATHNAME_LEN];
    char path[MAX_PATHNAME_LEN], base[50], ext[5];
    char LocationKeep[MAX_PATHNAME_LEN];
    static unsigned long long index = 0;

    if(str)
    {
        if(FileExists(LOGFILE, &size))
        {
            strcpy(pn,LOGFILE);
            ManageLogs(pn, LOGSIZE);
            tmStr = calloc(25, sizeof(char));
            log = fopen(LOGFILE, "a+");
            if (log == NULL)
            {
                free(tmStr);
                return -1;
            }
            //fprintf(log, "%10llu %s: %s - %d\n", index++, GetTimeString(tmStr), str, GetClockCycles());
            fprintf(log, "%s: %s - %d\n", GetTimeString(tmStr), str, GetClockCycles());
            //fprintf(log, "%s: %s\n",  GetTimeString(tmStr), str);
            fclose(log);
            free(tmStr);
        }
        else
        {
            strcpy(LocationKeep, LOGFILE);
            GetFileParts(LocationKeep, path, base, ext);
            CheckAndOrCreateDirectories(path);
            tmStr = calloc(25, sizeof(char));
            log = fopen(LOGFILE, "a+");
            if (log == NULL)
            {
                free(tmStr);
                return -1;
            }
            fprintf(log, "%s: %s - %d\n", GetTimeString(tmStr), str, GetClockCycles());
            //fprintf(log, "%s: %s\n",  GetTimeString(tmStr), str);
            fclose(log);
            free(tmStr);
        }
    }
    return 0;
}  

Regarding: browsing the internet for the last 2 hours . 关于: 最近2个小时内浏览互联网 Next time try 下次尝试
"tutorial on writing to a file in C" in Google, it lists lots of links, including: This one... More On The Topic . Google的“关于用C编写文件的教程”中列出了许多链接,包括:这个... 更多关于主题的信息

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

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