gpt4 book ai didi

C - 程序只用 fprintf 写一行

转载 作者:太空宇宙 更新时间:2023-11-04 05:50:31 24 4
gpt4 key购买 nike

我正在尝试创建一个使用不同线程写入文件的程序。我写了下面的代码。

#include <time.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>


pthread_t thread_id;

void *write_file(void *arg) {
int number = (int) arg;
FILE *file_write = fopen("file.txt", "w");
fprintf(file_write, "Number: %d\n", number);
fclose(file_write);
printf("Thread Finalized\n");
return NULL;
}

int main() {
chdir("/");
srand(time(NULL));
int cont = 0;
while(1) {
int random_number = rand();
if(random_number % 5 == 0) {
cont++;
int response = pthread_create(&thread_id, NULL, write_file, (void *) random_number);
if(response != 0) {
printf("Can't create process\n");
} else {
printf("Thread created successfully\n");
}
}
sleep(1);
if(cont == 8) {
break;
}
}
return 0;
}

但是当我打开文件时,我发现只有一行如下:

Number: 1069822935

我期望的是该文件应包含 8 行随机数可被 5 整除。

谢谢。

最佳答案

你的文件模式不能那样工作。如果每个线程都在“w”中打开文件 - 写入 - 每个线程都会覆盖已经存在的任何内容。追加的“a”应该有效。

另请参阅:http://www.c4learn.com/c-programming/c-file-open-modes/

关于C - 程序只用 fprintf 写一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43419326/

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