gpt4 book ai didi

c - 使用 C 中的线程写入全局文件

转载 作者:行者123 更新时间:2023-11-30 17:36:32 25 4
gpt4 key购买 nike

我在写入全局创建的文件、在 main 中初始化(成功)以及写入多个线程使用的函数(在 Linux 上)时遇到问题。

#includes

FILE *f;
main(){
// Create threads successfully
f = fopen("fileName.txt", "w");
// Make sure the file was able to be created
if(f = NULL){
printf("Unable to create file");
exit(1);
}
// This much works, the check indicates the file was created
// successfully when I run it
while(1){
// loops for a while, getting input from user to direct threads
// When end is determined, waits for all the threads to finish,
// clears allocated memory, and closes file then returns
fclose(f);
return;
}


}

void *threadProcess(){
// Do stuff
// This printf works fine using the values i give the function, as is here
// The values are determined in 'Do stuff'
printf("%d trying to write \"%d BAL %d TIME %d.%06d %d.%06d\" to the file\n", cid, tmp->reqNum, balance, tmp->seconds, tmp->useconds, endTime.tv_sec, endTime.tv_usec);
fflush(stdout);

// There appears to be a Segmentation fault here
fprintf(f, "%d BAL %d TIME %d.%06d %d.%06d\n", tmp->reqNum, balance, tmp->seconds, tmp->useconds, endTime.tv_sec, endTime.tv_usec);
// Never gets here
}

我在这里做错了什么?正如我所说,fprintf 语句之前的 printf 语句有效并输出正确的内容。

我是否错误地假设这将确保我不会遇到 fprintf 的指针问题?

谢谢

最佳答案

它在我的 if(reqLog = NULL) 检查中......我正在分配而不是比较。抱歉浪费了您的时间哈哈。 – 汤普森

关于c - 使用 C 中的线程写入全局文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22646866/

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