Hi, I am doing a forum in C as my mini project. The idea is like any other forum. A user enters a query and other users reply to it. But it creates a problem here. After adding queries, if I wish to reply to query in between then it adds a redundant entry in file. 1st entry is the original query without reply and 2nd entry is the same query now with a reply added.
I want only 1 entry of the query along with replies.
Here is the code:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include "var.c"
int check_count();
void add_query();
void add_reply();
void view_all();
void main()
{
int user_typ,op_typ;
clrscr();
printf("\nWELCOME\n");
recsize=sizeof(q);
while(op_typ!=0)
{
printf("\n\n1.Add a new entry\n2.View all entries\n3.Reply to an entry\n0.Exit");
printf("\nEnter your choice here");
scanf("%d",&op_typ);
switch(op_typ)
{
case 1:
{
add_query();
}
break;
case 2:
{
view_all();
}
break;
case 3: add_reply();
break;
}
}
}
//Check the count of query to be posted
int check_count()
{
FILE *qp;
qp=fopen("queries.txt","rb+");
while(fread(&q,sizeof(q),1,qp)==1)
{
}
return q.qid+1;
}
//add a new query
void add_query()
{
FILE *fp;
int query_no,u_cat;
fp=fopen("queries.txt","ab+");
if(fp==NULL)
{
printf("\nError in creating/opening file");
}
query_no=check_count();
q.qid=query_no;
printf("\nEnter query no. %d: ",q.qid);
fflush(stdin);
gets(q.question);
printf("\nselect which category you belong to:\n1.Student\n2.Professor\n3.Expert");
printf("\nEnter your input here: ");
scanf("%s",q.user_cat);
fseek(fp,0,SEEK_END);
fwrite(&q,sizeof(q),1,fp);
fclose(fp);
printf("\nYou entered: %s ",q.question);
printf("\nCategory: %s ",q.user_cat);
}
//Display queries posted
void view_all()
{
FILE *fp;
fp=fopen("queries.txt","rb+");
clrscr();
if(fp==NULL)
printf("\nCannot open file");
while(fread(&q,sizeof(q),1,fp)==1)
printf("\nQuery No.%d\nQuery: %s\nCategory: %sReply: %s\n\n",q.qid,q.question,q.user_cat,q.reply);
fclose(fp);
}
void add_reply()
{
FILE *fp,*fr;
char another,ch;
int query_id;
another='Y';
fp=fopen("queries.txt","a+");
fr=fopen("replies.txt","w+");
if(fp==NULL)
{
printf("\nCannot open file");
}
if(fp==NULL)
printf("\nCannot open file");
while(another=='Y')
{
printf("\nEnter the query no. to which you wish to add a reply: ");
scanf("%d",&query_id);
while(fread(&q,sizeof(q),1,fp)==1)
{
if(q.qid==query_id)
{
printf("\nQuery: %s",q.question);
printf("\nEnter your reply here: ");
fflush(stdin);
gets(q.reply) //The problem is here. Adds duplicate entries
fseek(fp,- sizeof(q),SEEK_CUR);
fwrite(&q,sizeof(q),1,fp);
break;
}
}
printf("\nAdd another reply?(Y/N)");
fflush(stdin);
another=getche();
}
}
This is the file var.c where I have declared the structure:
Code:
#include<stdio.h>
#include<conio.h>
struct query
{
int qid;
char question[3000];
char user_cat[20];
char reply[50][500];
};
struct query q;
long int recsize;
Kindly advise.
Thanx