C编程输出文本文件 [英] C Programming output text file
问题描述
我刚刚开始编程,并且有一个初学者的问题: 我想更好地了解fprint()函数的工作原理,因为有时当我用它创建一个文本文件时,我意识到文件的类型多种多样(例如,只读,追加和写入).而且,当我想用循环创建的文件上写内容时,添加内容的顺序似乎会改变
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+");
如果是
file = fopen(name,"w");
那么创建文本文件最方便的方法是什么? 谢谢!
So what's the most convenient way to create a text file? Thank you!
所以说我想写一个trie树中的所有单词,文本文件中的顺序将不同于仅用print()替换fprint() 我有一个树的全局节点,还有一个指向它的其他函数的节点指针
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));
函数是:
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);
}
节点:
struct node{
struct node * parent;
int noempty;
int isword;
int super;
int occurrence;
int leaf;
struct node * child[26];
};
最后是插入功能
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;
};