简体   繁体   English

IO:同时从C ++程序和另一个Java程序写入和读取相同的文本文件吗?

[英]IO : Writing and reading to the same text file from a C++ program and from another Java program simultaneously?

Is it possible to read and write to the same text file with both a C++ application and a java application at the same time without writing conflicting lines / characters to it ? 是否可以使用C ++应用程序和Java应用程序同时读取和写入相同的文本文件,而不会在其中写入冲突的行/字符? I have tested with two java applications for now, and it seems like it's possible to write to the file from one process even if the other process has opened the stream, but not closed it. 我现在已经用两个Java应用程序进行了测试,似乎可以从一个进程写入文件,即使另一个进程打开了流但没有关闭它也是如此。 Are there any way to lock the file so that the other process needs to wait ? 有什么方法可以锁定文件,以便其他进程需要等待吗?

For two processes that are writing to the same file, as long as you flush your output buffers on line boundaries (ie, flush after you write a newline character sequence), the data written to the file should be intervleaved nicely. 对于正在写入同一文件的两个进程,只要在行边界上刷新输出缓冲区(即,在写换行符序列后刷新),就应该很好地交错写入文件的数据。

If one process is writing while another is reading from the same file, you just have to ensure that the reads don't get ahead of the writes. 如果一个进程正在写而另一个进程正在从同一个文件读取,则只需确保读取不超过写入。 If a read gets an end-of-file condition (or worse, a partial data line), then you know that the reading process must wait until the writing process has finished writing another chunk of data to the file. 如果读取得到文件结束条件(或更糟糕的是,出现了部分数据行),则您知道读取过程必须等到写入过程完成将另一数据块写入文件为止。

If you need more complicated read/write control, you should consider some kind of locking mechanism. 如果您需要更复杂的读/写控制,则应考虑某种锁定机制。

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

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