我最初认为写入/从配置文件写入会很慢,我对写入/从数据库有类似的想法。虽然提供了一些很好的建议:sqlite 和配置文件解析器,但最终我决定以老式方式向文本文件写入/读取几行代码不会那么昂贵。
在将这些概念合并到我的编辑器中之前,我整理了一个演示程序,我在下面提供了该程序。随意批评这个程序,特别是在内存使用方面。该程序演示了以下步骤:
(如果我列出一个列表,它似乎会弄乱我的代码块)
1)检查配置文件是否存在,2)如果存在则删除配置文件,3)将路径写入配置文件,4)从配置文件中读取路径
/*
* Compile Command:
* gcc ledit_config.c -o ledit_config
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // system
#define NUM_TABS 10
char paths[NUM_TABS][200];
void write_config();
void read_config();
int main ()
{
write_config();
read_config();
}
void write_config()
{
char *config_file;
char temp[200];
int i=0;
/* change to the user's home directory (for fopen) */
(int)chdir(getenv("HOME"));
config_file = ".config/ledit/files";
/* populate paths array with random paths */
strcpy(paths[0], "~/Documents/code/glade/tutorial1/scratch_files/scratch.py");
strcpy(paths[4], "~/Documents/code/glade/tutorial1/scratch_files/scratch.c");
strcpy(paths[7], "~/Documents/code/glade/tutorial1/scratch_files/scratch.glade");
if (fopen(config_file, "r") == NULL) /* file does not exist */
{
system("mkdir -p $HOME/.config/ledit/");
FILE *fp;
fp=fopen(config_file, "w");
for(i = 0;i < NUM_TABS;++i)
{
strcpy(temp,paths[i]);
strcat(temp, "\n");
if (strlen(temp) > strlen("\n")) /* check to see if element actually contains more than just "\n" */
{
fprintf(fp, "%s",temp);
}
}
fclose(fp);
}
else /* file does exist */
{
system("rm $HOME/.config/ledit/files");
FILE *fp;
fp=fopen(config_file, "w");
for(i = 0;i < NUM_TABS;++i)
{
strcpy(temp,paths[i]);
strcat(temp, "\n");
if (strlen(temp) > strlen("\n")) /* check to see if element actually contains more than just "\n" */
{
fprintf(fp, "%s",temp);
}
}
fclose(fp);
}
}
void read_config()
{
char line[200];
char *config_file;
int i=0;
/* change to the user's home directory (for fopen) */
(int)chdir(getenv("HOME"));
config_file = ".config/ledit/files";
/* empty the paths array */
for(i = 0;i < NUM_TABS;++i)
strcpy(paths[i], "");
/* read the config file and poplulate array */
i = 0;
FILE* fp = fopen(config_file,"r");
while(fgets(line,sizeof(line),fp) != NULL)
{
strcpy(paths[i], line);
i++;
}
fclose(fp);
/* print out paths array for verification */
for(i = 0;i < NUM_TABS;++i)
printf("%s",paths[i]);
}