2013-11-03 66 views
0

我正在使用兩個獨立的線程使用一個程序來編寫1-500和500-1000的總和。我需要將輸出寫入由程序本身創建的文本文件。當我運行程序時,它會根據給定的名稱創建文件,但是我沒有根據需要獲取輸出。它只寫一行到文本文件。這是500-1000的總和。但是當我使用控制檯得到輸出時,它會根據需要顯示答案。如何克服這個問題。謝謝!使用fprintf()寫入文本文件()

#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"); 
     } 
    } 
} 

回答

1

它是因爲你打開同一個文件兩次,每個線程上一次。他們正在覆蓋彼此的工作。

爲了解決這個問題,您可以:

  1. 使用a+模式上fopen()追加新的生產線,結束現有的文件,或者;

  2. 打開main()中的文件,線程將只有fprintf()它。

+0

非常感謝。你解決了我的問題。 :) –