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

标签 c multithreading fopen printf

我正在使用一个程序使用两个单独的线程编写 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() 访问它。

关于c - 使用 fprintf() 在 C 中写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19749877/

相关文章:

c - Linux 模块 __must_check 注解

C 参数传递 - 提出的解决方案

c - 如何为预处理器创建变量值 channel ?

c++ - 我可以在单读/单写队列中用 volatile 替换原子吗?

asp.net - 是ASP.NET多线程的(如何执行请求)

c++ - 如何在不同的线程中执行 QTcpSocket?

c - 段错误,while 循环中的 fgets

捕获操作码 0xCC 作为异常

c - 无法在 C 中打开文件

无法以附加或写入模式打开文件