首页 > 解决方案 > 我正在尝试了解如何使用数组处理 texfiles 中的数字

问题描述

我正在尝试编写一个使用线程并允许我将数字从键盘输入文本文件然后显示它们的简单程序。我是编码新手,并试图在线程上自学。一切正常,直到程序尝试从文本文件中获取最后一个数字并找到阶乘。我可以输入任何数字,但程序总是认为文件中的最后一个数字是 0。

我的输出看起来像:

count = 120
Second thread takes the last digit: 0
Second thread finds factorial of that digit: 1
Second thread writes it in the file as a new last digit
120
1

我的代码:

#include <pthread.h>
#include <stdio.h>
#define N 80

int count;
int atoi(const char *nptr);
void *potok(void *param);
void *potok2(void *param);
FILE *file;
char arr[N];
pthread_mutex_t lock;

int main(int argc, char *argv[])
{
  pthread_t tid;
  pthread_t tid2;
  pthread_attr_t attr;

  if (argc != 2)
  {
    fprintf(stderr, "usage: progtest <integer value>\n");
    return -1;
  }

  if (atoi(argv[1]) < 0)
  {
    fprintf(stderr, "Argument %d can't have negative value\n",atoi(argv[1]));
    return -1;
  }

  pthread_attr_init(&attr);
  pthread_mutex_init(&lock,NULL);
  pthread_create(&tid,&attr,potok,argv[1]);
  pthread_join(tid,NULL);
  printf("count = %d\n",count);

  pthread_create(&tid2,&attr,potok2,NULL);
  pthread_join(tid2,NULL);

  pthread_mutex_destroy(&lock);

  file = fopen("hello.txt", "r");
  while (fgets(arr,N,file) != NULL)
  {
    printf("%s", arr);
  }
}

void *potok(void *param)
{
  int i, upper = atoi(param);
  count = 0;

  if (upper > 0)
  {
    for (i = 1; i <= upper; i++)
    count += i;
  }
  pthread_mutex_lock(&lock);
  file = fopen("hello.txt", "a");
  fprintf(file, "%i\n", count);
  fclose(file);
  pthread_mutex_unlock(&lock);
  pthread_exit(0);
}

void *potok2(void *param)
{
  char arr2[N];
  int c,f=1;
  int b = 0;
  pthread_mutex_lock(&lock);
  file = fopen("hello.txt", "a");
  while (fgets(arr2,N,file) != NULL)
  {
    b++;
  }
  printf("Second thread takes the last digit: %d\n", arr2[b]);
  for (c = 1; c <= arr2[b]; c++)
  {
    f = f * c;
  }
  printf("Second thread finds factorial of that digit: %d\n", f);
  printf("Second thread writes it in the file as a new last digit\n");
  fprintf(file,"%i\n",f);
  fclose(file);
  pthread_mutex_unlock(&lock);
  pthread_exit(0);
}

标签: cmultithreadingfactorial

解决方案


推荐阅读