使用fprintf()在C中写入文本文件

使用fprintf()在C中写入文本文件,c,multithreading,fopen,printf,C,Multithreading,Fopen,Printf,我正在使用一个程序,使用两个单独的线程编写1-500和500-1000的总和。我需要将输出写入由程序本身创建的文本文件中。当我运行程序时,它会根据给定的名称创建文件,但我没有得到所需的输出。它只向文本文件写入一行。这是500-1000的总和。但当我使用控制台获得输出时,它会根据需要显示答案。如何克服这个问题。谢谢 #include <stdio.h> #include <pthread.h> #include <fcntl.h> #include <st

我正在使用一个程序,使用两个单独的线程编写1-500和500-1000的总和。我需要将输出写入由程序本身创建的文本文件中。当我运行程序时,它会根据给定的名称创建文件,但我没有得到所需的输出。它只向文本文件写入一行。这是500-1000的总和。但当我使用控制台获得输出时,它会根据需要显示答案。如何克服这个问题。谢谢

#include <stdio.h>
#include <pthread.h>
#include <fcntl.h>
#include <stdlib.h>

#define ARRAYSIZE 1000
#define THREADS 2

void *slave(void *myid);

/* shared data */
int data[ARRAYSIZE];    /* Array of numbers to sum */
int sum = 0;
pthread_mutex_t mutex;/* mutually exclusive lock variable */
int wsize;              /* size of work for each thread */
int fd1;
int fd2;
FILE * fp;
char name[20];

/* end of shared data */

void *slave(void *myid)
{

    int i,low,high,myresult=0;

    low = (int) myid * wsize;
    high = low + wsize;

    for(i=low;i<high;i++)
        myresult += data[i];
        /*printf("I am thread:%d low=%d high=%d myresult=%d \n",
        (int)myid, low,high,myresult);*/
    pthread_mutex_lock(&mutex);
    sum += myresult; /* add partial sum to local sum */

    fp = fopen (name, "w+");
    //printf("the sum from %d to %d is %d",low,i,myresult);
    fprintf(fp,"the sum from %d to %d is %d\n",low,i,myresult);
    printf("the sum from %d to %d is %d\n",low,i,myresult);
    fclose(fp);

    pthread_mutex_unlock(&mutex);

    return;
}
main()
{
    int i;
    pthread_t tid[THREADS];
    pthread_mutex_init(&mutex,NULL); /* initialize mutex */
    wsize = ARRAYSIZE/THREADS; /* wsize must be an integer */

    for (i=0;i<ARRAYSIZE;i++) /* initialize data[] */
        data[i] = i+1;

    printf("Enter file name : \n");
    scanf("%s",name);
    //printf("Name = %s",name);
    fd1=creat(name,0666);
    close(fd1);

    for (i=0;i<THREADS;i++) /* create threads */
        if (pthread_create(&tid[i],NULL,slave,(void *)i) != 0)
            perror("Pthread_create fails");

    for (i=0;i<THREADS;i++){ /* join threads */
        if (pthread_join(tid[i],NULL) != 0){
            perror("Pthread_join fails");
        }
    }
}
#包括
#包括
#包括
#包括
#定义数组化1000
#定义线程2
void*slave(void*myid);
/*共享数据*/
整型数据[ARRAYSIZE];/*要求和的数字数组*/
整数和=0;
pthread_mutex_t mutex;/*互斥锁变量*/
int wsize;/*每个线程的工作大小*/
int-fd1;
int-fd2;
文件*fp;
字符名[20];
/*共享数据结束*/
void*从(void*myid)
{
int i,低,高,myresult=0;
低=(int)myid*wsize;
高=低+wsize;

对于(i=low;i这是因为您要打开同一个文件两次,每个线程打开一次。它们正在覆盖彼此的作业

要解决此问题,您可以:

  • 使用
    fopen()
    上的
    a+
    模式将新行追加到现有文件的末尾,或

  • main()
    中打开该文件,线程将仅
    fprintf()
    对其执行操作