I was so pleased with myself getting this to work last night without any errors or warnings on my first try too! But, of course, I changed a bunch of stuffed and screwed it up…
When I tried to gdb it, the list from this.ytxt seemed load to memory just fine. I think the problem was writing it. Now. it works again but only writes the first line of the file. I commented out whole functions and printf’d test marks and still couldn’t figure it out.
the idea is to read a variable number of lines from a file and print them in pairs. (Actually
it was meant to be like study flashcards but I never got around to that part)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct member{ //This emulates a dictionary
char key[20]; //and links each word+definition pair to the next pair.
char def[20];
struct member *ptr;
};
struct member *root;
struct member *curr;
FILE *f;
int fill_list(){ //Fill each member struct with next two lines of
curr=root;
char this[20]; //FILE *f
while(EOF){
if(!fgets(this,20,f)) break;
strcpy(curr->key,this);
if(!fgets(this,20,f)) break;
strcpy(curr->def,this);
curr=curr->ptr;
curr=malloc(sizeof(struct member));
curr->ptr=0;
}
return 0;
}
void free_all(){
curr=NULL;
while(curr!=root){
curr=root;
while(curr->ptr)curr=curr->ptr;
free(curr);
}
}
int terminate(int i){ //The terminate function closes file and
free_all(); //frees malloc'd memory, then returns main func's
fclose(f); //return value.
return i;
}
int main(){
f=fopen("this.txt","r");
if(!f)return -1;
root=malloc(sizeof(struct member));
root->ptr=NULL;
fill_list();
curr=root;
if ( curr != 0 ) {
while ( curr != 0 ) {
printf( "%s", curr->key );
curr = curr->ptr;
}
}
free_all();
return terminate(0);
}
Elaborating on Chad’s answer, you could have:
EDIT: thought I’d just add that if I was going to make slight modifications to your code this is what I’d do. If I were to do it from scratch I wouldn’t structure the loop that way or have unnecessary global variables like curr. Same goes for the point made by sarnold where you only have a single temporary buffer. Not to mention that your last entry in the list could be invalid; it might be a better idea to allocate the next member entry in the list only after you successfully read the two strings into two temporary buffers.