簡體   English   中英

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

[英]writing to a text file in C using fprintf()

我正在使用一個程序使用兩個單獨的線程編寫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");
        }
    }
}

這是因為您打開同一文件兩次,每個線程一次。 他們正在覆蓋彼此的工作。

要解決此問題,您可以:

  1. fopen()上使用a+模式將新行追加到現有文件的末尾,或者

  2. main()打開文件,線程僅將fprintf()移至該文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM