hello everyone
I have a problem with a code I have tried. The code I have tried. The code's objective is this. Read the 3 categories of text from a text file (test.txt) by using 3 separate threads and display them on the terminal.
Amber
John
Damien
Paul
Kyle
sydney
melbourne
canberra
perth
darwin
20
23
21
32
24
The program I wrote reads a string like this,
12345ABCDE!@#$%
So I need some help modifying this program to achieve the above.
It would mean a lot if someone could help me solve this problem as this is the best solution I could come up with.
Thank you for any help.
Output I am trying to get...
Amber from Sydney. Age: 20
John from Melbourne. Age: 23
Damien from Canberra. Age: 21
Paul from Perth. Age: 32
Kyle from Darwin. Age: 24
Code:
#include <stdio.h>
#include <pthread.h>
#define LENGTH 5
pthread_mutex_t lock;
pthread_t t[3];
struct tcontainer
{
// the filename
const char* name;
// what are we reading
int offset;
// buffers
char nums[LENGTH];
char alphas[LENGTH];
char syms[LENGTH];
};
typedef struct tcontainer container;
// the thread
void* reader_threadf(void* cont_p)
{
FILE *fp ;
container* co=(container*)cont_p;
char *data_o;
int offset;
// protect offset
pthread_mutex_lock(&lock);
offset=co->offset;
co->offset++;
pthread_mutex_unlock(&lock);
//open the file
fp=fopen(co->name, "r");
//determine which buffer extract into
if (offset==2)data_o=co->syms; else {if (offset==1)data_o=co->alphas; else data_o=co->nums;}
// move the seek to the position determined by offset
fseek( fp, LENGTH*offset, SEEK_SET );
// reads the data from the offset
int i=0;
while(i<LENGTH)
{
data_o[i]=fgetc(fp);
i++;
}
fclose(fp);
return NULL;
}
int main()
{
container co;
co.offset=0;
co.name="test.txt";
// launch threads
for (int i=0;i<3;i++)
pthread_create(&(t[i]), NULL, &reader_threadf, (void*)&co);
// finish threads
for (int i=0;i<3;i++)
pthread_join(t[i],NULL);
// output data
for (int i=0;i<LENGTH;i++)
{
printf("%c",co.nums[i]);
printf("%c",co.alphas[i]);
printf("%c\n",co.syms[i]);
}
return 0;
}
I have to use getline instead (instead of the getc), and redo the container buffers into [LENGTH][MAXNAMESIZE] or something like that. And the seek has to adjusted to the proper position. These are the stuff I need help with.