gpt4 book ai didi

c - 如何强制 fseek() 移动光标

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:08 29 4
gpt4 key购买 nike

我有一个创建多个线程的程序,每个线程都试图在不同位置(偏移)的文件中写入 100 个字节。第一个线程从0开始写100字节,第二个100字节从100开始,第三个100字节从300开始等等如果线程按此顺序执行,则一切正常,我不需要 fseek。但是对于实时并发,如果我将第一个线程置于“sleep(2)”状态 2 秒,等待所有其他线程完成,然后使用 fseek 将文件光标移动到文件开头,这不会发生。我使用互斥体来处理并发。代码示例:

    offset=0;//for the first thread
char data[100];
int length; // how many chars are currently in data
FILE * f;

pthread_mutex_lock(&mutexFileWrite);
f = fopen(fileName, "a");
fseek(f,offset, SEEK_SET);
fwrite(data,sizeof(char),length,f);
fclose(f);
pthread_mutex_unlock(&mutexFileWrite);

最佳答案

如果您不打算只追加文件,请不要以追加模式打开文件。

来自 fopen 的 POSIX 引用:

Opening a file with append mode (a as the first character in the mode argument) shall cause all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to fseek().

看起来您正在寻找 r+ 模式。

关于c - 如何强制 fseek() 移动光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14081265/

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