我无法写入已全局创建的文件,无法在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/

10-11 22:37
查看更多