Hi I just started programming and have a beginner question: I would like to better understand how the fprint()function work because sometimes when I create a text file with it, I realized there are various types of file eg.(read only, append and write). And when I want to write on the file I created with a loop, the order in which the content is added seem to change when I do
file = fopen(name,"a+");
And I cannot add all the content in the loop if it is
file = fopen(name,"w");
So what's the most convenient way to create a text file? Thank you!
So say I want to write all the words from a trie tree, the order in the text file would be different than just replacing fprint() with print() I have a global node for the tree and a node pointer pointing to it for other functions
struct node *root = (struct node *)malloc(sizeof(struct node));
And the function is:
void printResult(struct node* r){
struct node *p = r;
FILE *file;
sprintf(name, "man%d.txt", num);
file = fopen(name,"a+");
int i=0;
int temp;
while(i!=26){
if(p->child[i]==NULL){
i++;
continue;}
if(p->child[i]->isword==1&&p->child[i]->leaf==1){
word[k]=i+'a';
word[k+1]='\0';
fprintf(file,"%s", word);fprintf(file,"%s"," " );
fprintf(file,"%d", p->child[i]->occurrence);fprintf(file,"%s"," " );
fprintf(file,"%d\n", p->child[i]->super);
i++;
continue;}
if(p->child[i]->isword==0){
word[k]=i+'a';
temp=k;
k++;
p=p->child[i];
printResult(p);
k=temp;
p=p->parent;
}
if(p->child[i]->isword==1&&p->child[i]->leaf==0){
word[k]=i+'a';
word[k+1]='\0';
temp=k;
k++;
p->child[i]->isword=0;
fprintf(file,"%s", word);fprintf(file,"%s"," " );
fprintf(file,"%d", p->child[i]->occurrence);fprintf(file,"%s"," " );
fprintf(file,"%d\n", p->child[i]->super);
p=p->child[i];
printResult(p);
k=temp;
p=p->parent;
}
i++;
}fclose(file);
}
And the node:
struct node{
struct node * parent;
int noempty;
int isword;
int super;
int occurrence;
int leaf;
struct node * child[26];
};
Lastly it's the insert function
struct node* insert(struct node *root,char *c){
int i=0;
struct node *temp=root;
int l=length(c);
while(i!=l){
int index=c[i]-'a';
if(temp->child[index]==NULL){
//New Node
struct node *n=(struct node *)malloc(sizeof(struct node));
n->parent=temp;
temp->child[index]=n;
temp->noempty=1;}
//Node Exist
if(i!=l&&temp->leaf==1){temp->leaf=0;}
temp=temp->child[index];
i++;}
if(temp->noempty==0){
temp->leaf=1;}
temp->isword=1;
return root;
};
fopen(name, "w")is most convenient."a"mode). If you mean 'insert a line at the start of the file (pushing the previous lines down the file)', then it is not sensibly doable; it rapidly gets very expensive.fprintf(file,"%s", word);fprintf(file,"%s"," " ); fprintf(file,"%d", p->child[i]->occurrence);fprintf(file,"%s"," " ); fprintf(file,"%d\n", p->child[i]->super);— should be one call: ` fprintf(file,"%s %d %s\n", word, p->child[i]->occurrence, p->child[i]->super);`