【发布时间】:2021-08-15 03:37:02
【问题描述】:
我正在用 c 编写一个简单的文本编辑器,我定义了一个名为 node 的结构并创建了一个名为 textbuffer 的链表。我正在尝试为文本编辑器创建一个插入函数。到目前为止的代码如下:
#include <stdio.h>
#include <string.h>
struct node
{
char statement[40];
int next;
};
struct node textbuffer[25];
int free_head;
int inuse_head;
void insert(int line, char* stat)
{
FILE *file;
file=fopen("texteditor.txt","w");
if(file!=NULL)
{
int i;
int k;
strcpy(textbuffer[line].statement,stat);
textbuffer[line].next=line+1;
fprintf(file,textbuffer[line].statement);
for(i=0;i<=25;i++)
{
if(textbuffer[i].statement==NULL)
{
free_head=i;
break;
}
}
for(k=0;k<=25;k++)
{
if(textbuffer[k].statement!=NULL)
{
inuse_head=k;
break;
}
}
}
else
{
printf("File couldn't found.");
}
fclose(file);
}
int main()
{
insert(1,"Hello World");
return 0;
}
问题是当 texteditor.txt 文件为空时,当我运行代码时它会在文件中写入“Hello World”,这很好,但是当我第二次运行它时,我希望它会写入“HelloWorldHelloWorld”但它什么也没做。它仍然是“Hello World”。我该如何解决这个问题?
【问题讨论】:
-
查看打开文件时可以使用的不同模式。 en.cppreference.com/w/cpp/io/c/fopen
"w"模式会破坏现有文件的内容。 -
您使用索引而不是指针进行链接。有趣的。我从未见过它,甚至从未想过这种可能性。有什么特别的原因吗?