【发布时间】:2017-03-01 03:36:39
【问题描述】:
您好,我刚开始编程,有一个初学者问题: 我想更好地理解 fprint() 函数是如何工作的,因为有时当我用它创建一个文本文件时,我意识到有各种类型的文件,例如(只读、追加和写入)。当我想在循环创建的文件上写入内容时,添加内容的顺序似乎发生了变化
file = fopen(name,"a+");
如果是,我不能在循环中添加所有内容
file = fopen(name,"w");
那么创建文本文件最方便的方法是什么? 谢谢!
假设我想写出 trie 树中的所有单词,文本文件中的顺序与将 fprint() 替换为 print() 不同 我有一个树的全局节点和一个指向它的节点指针以用于其他功能
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;
};
【问题讨论】:
-
我不明白你的问题。如果您以“a”模式打开文件,则所有写入都将转到文件末尾。如果您以“w”模式打开,那么所有写入都将转到您执行写入时的当前位置。如果您以“r”模式打开,则写入将失败。创建文件的“最方便”的方式取决于您希望写入的行为方式。可能
fopen(name, "w")最方便。 -
@WilliamPursell 如果我想创建一个文件并写入文件顶部怎么办?我正在尝试编写一个函数,当我使用 print() 时,顺序是正确的,但是当我使用 fprint() 以相同的顺序将它们写入文件时,它不起作用,而且顺序似乎真的很随机。
-
“写入文件顶部”是什么意思?如果您的意思是“重复更改第一行”,这是可行的(但不适用于
"a"模式)。如果您的意思是“在文件开头插入一行(将前面的行向下推到文件中)”,那么它是不可行的;它很快变得非常昂贵。 -
对不起,我在评论中写错了,我的意思是逐行写内容
-
五个调用——
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);——应该是一个调用:` fprintf(file,"%s %d %s\n", word, p->child[i]->occurrence, p->child[i]->super);`