reading string and integers from file - c

I have been trying to read some strings and integers from a file,but it seems that I don't do it correctly...This programm is supposed to read data from a file...It must create a list with the names of writters.For every writter,it should use a struct like the one I used here...Foe every writter's text,I must also create a struct,like the one I did here..Then,I have to sort the list,create another list with the most popular writers and then print the output...My program is:
#include<stdio.h>
#include<math.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
struct AuthorRecord {
char textTitle[30];
long Download;
struct AuthorRecord *next;
};
typedef struct AuthorRecord *AuthorRecordType;
typedef struct {
char firstName[30];
char lastName[30];
int idNumber,s1;
long s2;
float p;
AuthorRecordType text;
} AuthorType;
struct MemberNodeStruct {
AuthorType *anAuthor;
struct MemberNodeStruct *next;
};
typedef struct MemberNodeStruct *MemberNodeType;
int main()
{
int m,n,i,j,d,z,e,y;
long k;
char s[30];
AuthorType *a;
struct MemberNodeStruct *l,*l2,*temp,*min,*b1,*b2,*r,*r2,*r3;
struct AuthorRecord *t,*t2,*h,*h2,*min2,*temp2;
FILE *f;
f=fopen("project.txt","rt");
if(f==NULL)
exit(-1);
l2=NULL;
t2=NULL;
t=NULL;
fscanf(f,"%d",&n);
getchar();
for(i=1;i<=n;i++)
{
y=0;
a=(AuthorType*)malloc(sizeof( AuthorType));
fgets(s,30,f);
strcpy(a->firstName,s);
fgets(s,30,f);
strcpy(a->lastName,s);
fscanf(f,"%d",&d);
getchar();
a->idNumber=d;
fscanf(f,"%d",&m);
getchar();
t2=NULL;
a->s1=m;
a->s2=0;
for(j=1;j<=m;j++)
{
t=(struct AuthorRecord*)malloc(sizeof(struct AuthorRecord));
fgets(s,30,f);
e=0;
h=t2;
while(e==0 && h!=NULL)
{
if(strcmp(h->textTitle,s)==0)
{
e=1;
h2=h;
}
else
h=h->next;
}
if(e==0)
{
strcpy( t->textTitle,s);
fscanf(f,"%ld",&k);
getchar();
t->Download=k;
a->s2=a->s2+t->Download;
t->next=t2;
t2=t;
}
else
{
y=y+1;
fscanf(f,"%ld",&k);
getchar();
h2->Download=h2->Download+k;
a->s2=a->s2+k;
}
}
a->s1=a->s1-y;
a->p=round(a->s2/a->s1);
a->text=t2;
l=(struct MemberNodeStruct*)malloc(sizeof(struct MemberNodeStruct));
l->anAuthor=a;
l->next=l2;
l2=l;
}
........ (150 more lines of code)
.....
system("pause")
return(0);
I have tried this program with scanf and gets instead of a file and fscanf and fgets and it worked correctly...That's the reason I don't write the rest of my code.
project.txt is:
5
Julius Caesar 101
2
DeBelloGallico
3000
DeBelloCivili
8000
Sun Tzu 544
3
TheArtOfWar
5000
TheArtOfWar
5000
Strategems
3000
Plato Athenian 427
4
TrialOfSocrates
10000
Symposium
15000
TheRepublic
7000
Apology
9000
Gaius Suetonius 69
3
thetwelvecaesars
7000
dePoetis
500
DeClarisRhetorebus
1000
Orestis Mastakas 1995
1
WhyDidRomePrevail
15
Whenever I run this program,it ends up in a failure...For some reason,it demands input from me...I tried to remove the getchar() but still, it didn't work! What should I do?

It reads input from stdin, because you told it to do that :
fscanf(f,"%d",&n);
getchar();
Try making sure, you don't have anything reading input from default (file descriptor 0).
If you need to read 1 char from f, then use fgetc instead of getchar.

Related

my binary file is always empty when i try to fill it with an array

typedef struct equipement_agricole{
char type[20];
char marque[20];
char modele[20];
char numero_serie[30];
char panne[20];
char status[20];
int nb_status;
int nb_panne;
}equipement_agricole;
typedef struct eq_util{
char numero_s[30];
char type_u[20];
char marque_u[20];
char modele_u[20];
int nb_util;
int ordre;
}eq_util;
typedef struct verif{
char id[30];
int nb;
}verif
void equipement_plus_util()
{
FILE *f;
FILE *g;
int i=0;
int taille=0;
f=fopen("equipement.bin","rb");
g=fopen("equipement_util.bin","wb");
equipement_agricole E;
eq_util U;
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
{
taille+=1;
}
verif tab1[taille];
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
{
strcpy(tab1[i].id,E.numero_serie);
tab1[i].nb=E.nb_status;
i++;
}
int j,k;
verif T;
for(j=0;j<taille-1;j++)
{
for(k=j+1;k<taille;k++)
{
if(tab1[j].nb<tab1[k].nb)
{
strcpy(T.id,tab1[j].id);
T.nb=tab1[j].nb;
strcpy(tab1[j].id,tab1[k].id);
tab1[j].nb=tab1[k].nb;
strcpy(tab1[k].id,T.id);
tab1[k].nb=T.nb;
}
}
}
int a;
for(a=0;a<taille;a++)
{
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
{
if(strcmp(tab1[a].id,E.numero_serie)==0)
{
strcpy(U.marque_u,E.marque);
strcpy(U.modele_u,E.modele);
strcpy(U.numero_s,E.numero_serie);
strcpy(U.type_u,E.type);
U.nb_util=E.nb_status;
U.ordre=a+1;
fwrite(&U,sizeof(eq_util),1,g);
}
}
}
fclose(f);
fclose(g);
}
hi guys i need your help i've been stuck in this sccince 2 days i can't find a solution for this so my problem is
after i take the necessair information from equipement.bin bianry file and put it inside an array than i sort that array after that i put the array whit is i think sorted in the equipement_util.bin but i always find that it is always empty i tried every thin that i know thank you
regarding:
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
{
taille+=1;
}
verif tab1[taille];
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
When the first 'while()' loop exits, the 'file pointer' will be at the end of the file, So the second while() loop will exit immediately.
To fix this problem:
after the first while() loop exits, reset the 'file pointer' to the beginning of the file. Suggest:
rewind( f );
the above will result in the data from the file being set into the array tab1[]
There may be other problems, however the above correction will get your code started in the right direction

scanf data from a file and pass to struct

I'm trying to take a data from a file and store it in a struct. I use a string called buffer to get all text, and then I use a string called one_line to pass the data to the struct.
I added some explation in the code notes.
#include<stdlib.h>
#include<stdio.h>
#define N 10000
#define line 30
typedef struct player
{
char full_name[N];
int year[N];
char team_name[N];
} player;
void main()
{
char buffer[1000];//string to store all data from afile
char one_line[line];//string for a struct that take each line separate
player p[500];//array of struct
FILE *ptr;//pointer to file
int i=0,count_of_player=0;
ptr=fopen("player of the year.txt","r");
if(ptr==NULL)
{
printf("cant open ");
return;
}
while (fgets(buffer,N,ptr)!=NULL)//the buffer get all the text
{
while (one_line!='\0')//the string get one line in a time
{
fscanf(ptr,"%d %s %s",&(p[i].year),&(p[i].full_name),&(p[i].team_name));\\get date from file to struct
i++;
count_of_player++;
}
}
fclose(ptr);
while (buffer!=NULL)
{
printf("%s",buffer);
}
for (i=0;i<count_of_player;i++)
{
printf("%s won the best player trophy in %d at the team:%s",p[i].full_name,p[i].year,p[i].team_name);
}
}

Binary file update in c....fwrite does not write the whole struct successfully

I have a file which is opened for both write/read (fopen(name,"wb+")) which contains a load of the struct below
struct pedia
{
int code;
char descr[50];
int TM;
int pos;
int flag;
};
The whole file is initialized with codes from 0 to the size of the file (user gives the size)flags equal to 0 ,descr=" " and TM=pos=-1
When i ask the user to write the # of the registration he wants to update and i print the struct which is saved there it s printed correctly.
Also when i call the input function in which the user sets new values for every variable in the struct i print the code,descr etc. right after and they are changed successfully .
However when i use fwrite to write the struct to the file it only writes 1 item successfully in the file.
void fileupdate(FILE *f,int filesize)
{
struct pedia *field;
field=(struct pedia *)malloc(sizeof(struct pedia));
int k,key;
char opt[5];
int num=0;
while(1)
{
puts("\nUPDATE\n");
printf("\nType the # of the registration you want to update (key must be between 0 and %d) \n\nkey:",filesize);
scanf("%d",&key);
getchar();
if(key>=0 && key<=filesize)
{
fseek(f,sizeof(struct pedia)*key,SEEK_SET);
fread(field,sizeof(struct pedia),1,f);
printf("%d,%s,%d,%d,%d\n",field->code,field->descr,field->TM,field->pos,field->flag);
if(field->flag==0)
{
puts("type yes to register new info or no to cancel the update\n");
fgets(opt,sizeof(char)*5,stdin);
if(isspace(*(opt+strlen(opt)-1)))
*(opt+strlen(opt)-1)='\0';
if(strcmp(opt,"yes"))
continue;
printmask();
input(&field);
num=fwrite(field,sizeof(struct pedia),1,f);
printf("\n%d,%s,%d,%d,%d\n",field->code,field->descr,field->TM,field->pos,field->flag);
printf("num=%d\n",num);
}
}
}
There is no fseek() between fread() and fwrite(), so fwrite() doesn't overwrite the struct you wanted to update but the next one.

Copying unformatted file into structure

#define MAX 20
typedef char string20[21];
struct flight_list{
char fcode[21];
string20 srccity;
string20 descity;
int deptime[2];/** deptime[0] hours, deptime[1] minutes **/
int duration;
int eta[2];/**eta[0] hours , eta[1] minutes**/
int nctr;
};
void load_flight(struct flight_list flight[]){
int num,i;
char* ptr;
FILE* fp;
fp = fopen("flightFILES.txt","r");
fscanf(fp,"%d",&num);
while(!feof(fp)){
for(i=0;i<num;i++){
fgets(flight[i].fcode,100,fp);
fgets(flight[i].srccity,100,fp);
fgets(flight[i].descity,100,fp);
fscanf(fp,"%d %d",flight[i].deptime[0],flight[i].deptime[1]);
fscanf(fp,"%d",flight[i].duration);
fscanf(fp,"%d %d",flight[i].eta[0],flight[i].eta[1]);
ptr=strchr(flight[i].fcode,'=');
strcpy(flight[i].fcode,ptr+1);
ptr=strchr(flight[i].srccity,'=');
strcpy(flight[i].srccity,ptr+1);
ptr=strchr(flight[i].descity,'=');
strcpy(flight[i].descity,ptr+1);
}
}
fclose(fp);
}
every time I run this function It crashes I just followed what he advice me to do please help me I'm suppose to copy the contents inside of this file to my array of structures
the file format is this:
4
FCODE=CHIX
SRCCITY=MAN
DESTCITY=KAN
DEPARTURE=12 10
DURATION=30
FCODE=PAUL
SRCCITY=KAN
DESTCITY=CHG
DEPARTURE=13 10
DURATIOn=60
File input/output in C unformatted

hangman console game in c

#include<stdio.h>
#include<string.h>
#include<time.h>
#include<stdlib.h>
typedef struct dic {
int index;
char string[10];
struct dic *next;
}node;
main() {
FILE *fp;int indexrand;node *head;node *mainhead;
char s[10],question[10],answer[10];char check;
int count=-1,i,j,k,len,flag;head=(node *) malloc(sizeof(node));
mainhead=head;
fp=fopen("dictionary.txt","r");
while((fgets(s,10,fp))!=NULL) {
strcpy(head->string,s);
count++;
(head->index)=count;
head->next=(node *)malloc(sizeof(node));
head=head->next;
}
fclose(fp);
head->next=NULL;
srand(time(NULL));
indexrand=rand()%(count+1);
printf("%d\n",indexrand);
for(head=mainhead;(head->next)!=NULL;head=head->next)
if((head->index)==indexrand)
strcpy(question,(head->string));
printf("%s\n",question);
len=strlen(question);
printf("%d\n",len);
for(i=0;i<len-1;i++)
answer[i]='_';
answer[i]='\0';
printf("%s\n",answer);
printf("6 chances to go\n");
for(i=0,k=6;k>0;i++) {
flag=0;
printf("%d\n",i);
scanf("%c",&check);
for(j=0;j<(len-1);j++) {
if(question[j]==check) {
flag++;
answer[j]=check;
}
}
if(flag>0)
printf("%d chances to go\n",k);
if(flag==0) {
k--;
printf("no common letters...%d chances to go\n",k);
}
printf("%s\n",answer);
}
}
The file dictionary.txt has only one word per line.
While running the code, for every attempt from the user (i.e after user enters a character) the statement no common letters...%d chances to go\n",k is being displayed even if the flag > 0 condition is satisfied.
How do I correct this?
The line
scanf("%c",&check);
is reading characters the user types, including the newline.
You probably just want to read the first character on the line: use fgets() to read the whole line, and then set check = line[0].
printf("%d\n",i);
scanf("%c",&check);
Because of these statements,scanf is taking \n as a parameter and so printing "no common letters..." every time.Replace the above code with
printf("%d",i);
scanf("\n%c",&check);
I think you want to pass a string to scanf, so try it :
scanf("%s",&check);

Resources