gpt4 book ai didi

c - 在C中覆盖文件的内容

转载 作者:行者123 更新时间:2023-11-30 14:59:20 24 4
gpt4 key购买 nike

我正在编写一个 fork 多个进程的代码。他们都共享一个名为“字符”的文件。我想做的是让每个进程读取文件中的“唯一字符”,然后通过放置自己的字符来删除它,以便其他进程可以执行相同的操作。文件是进程相互通信的唯一方式。如何删除文件中的“唯一字符”并在其位置放置一个新字符。建议我使用 freopen() (它关闭文件并重新打开它并删除其以前的内容),但我不确定这是否是实现此目的的最佳方法。

最佳答案

您不必重新打开该文件。那对你没有任何好处。如果您担心每个进程缓冲输入或输出,如果您想使用基于 FILE * 的 stdio 函数,请禁用缓冲。

但是,如果我正确地阅读了您的问题(当文件中保存有特定值时,您希望每个进程替换文件中的一个字符,并且该值会针对每个进程进行更改),这将执行您的操作想要,使用 POSIX open() pread()pwrite() (您已经在使用 POSIX fork(),因此使用低级 POSIX IO 使事情变得更加简单 - 请注意 pread()pwrite() 消除了查找的需要。)

我会说这就是我认为您正在尝试做的事情:

// header files and complete error checking is omitted for clarity
int fd = open( filename, O_RDWR );

// fork() here?

// loop until we read the char we want from the file
for ( ;; )
{
char data;
ssize_t result = pread( fd, &data, sizeof( data ), 0 );

// pread failed
if ( result != sizeof( data ) )
{
break;
}

// if data read matches this process's value, replace the value
// (replace 'a' with 'b', 'c', 'z' or '*' - whatever value you
// want the current process to wait for)
if ( data == 'a' )
{
data = 'b';
result = pwrite( fd, &data, sizeof( data ), 0 );
break;
}
}

close( fd );

对于任何相当数量的进程,这都会给您的文件系统带来很大的压力。

如果您确实想从 fopen() 开始并使用该系列调用,则这可能会起作用,具体取决于您的实现:

FILE *fp = fopen( filename, "rb+" );

// disable buffering
setbuf( fd, NULL );

// fork() here???

// loop until the desired char value is read from the file
for ( ;; )
{
char data;

// with fread(), we need to fseek()
fseek( fp, 0, SEEK_SET );
int result = fread( &data, 1, 1, fp );
if ( result != 1 )
{
break;
}

if ( data == 'a' )
{
data = 'b';
fseek( fp, 0, SEEK_SET );
fwrite( &data, 1, 1, fp );
break;
}
}

fclose( fp );

同样,这假设我正确阅读了你的问题。请注意,John Bollinger 在有关多个句柄的评论中提到的 POSIX 规则并不适用 - 因为流明确未缓冲。

关于c - 在C中覆盖文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42864412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com