c - 我正在尝试了解如何使用数组处理 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);
}
解决方案
推荐阅读
- android - 一次打开两个应用程序只需单击一下
- node.js - 使用节点将数据写入文本文件
- alexa - Alexa:如何知道大响应在哪里被打断?
- highcharts - 如何沿着森伯斯特图表中的各个部分弯曲每个数据标签?
- javascript - 尝试对 GraphQL 数据进行 .map() 时,React Native 'undefined is not an object'
- laravel - 另一个“不能保存多个复选框”和“必须是数组类型,给定字符串”
- java - 使用java流,将两个具有相同键但不同值的映射合并到一个元组?
- android - 如何从我当前的位置查找数据库中的位置?
- latex - 如何以快捷方式将 Scilab 控制台中的矩阵转换为乳胶?
- android - 使用 handler.postDelayed 暂停程序后恢复