J
Jens
Hi All.
I am quite new to programming in C, comming from perl.
As an educational excersise I'm writing some code, which aims to change
the grub conf file menu.lst's default entry.
Consider the following code: (see code below)
If the new default entry line is longer than the original (e.g default 0,
changes to default 10, then one character of the next line is overwritten.
Is there a way of solving this progblem, without using a temp file?
Thx in advance
Jens
<code>
int alter_file(int timeout)
{
FILE *file;
regex_t *preg = malloc(sizeof(regex_t));
char *regex;
char *line;
line = (char*)malloc(sizeof(char)*257);
int ret;
regmatch_t* pmatch = (regmatch_t*)malloc(sizeof(regmatch_t));
size_t nmatch = 2;
regex = "^[[:blank:]]*default[[:blank:]]*([[:digit:]]*)";
ret = regcomp(preg,regex,REG_EXTENDED);
printf("ret %d",ret);
file = fopen("/boot/grub/menu.lst","r+");
if (file == NULL) { fprintf(stderr,"Couldn't open file for writing\n");
exit(1);}
while (fgets(line,256,file)!=NULL) {
ret = regexec(preg,line,nmatch,pmatch,0);
if (ret == 0) {
printf("end %d",pmatch[1].rm_eo+1);
fseek(file,(long)-(pmatch[1].rm_eo+1),SEEK_CUR);
fprintf(file,"%s","default 10\n");
}
}
return 0;
}
</code>
I am quite new to programming in C, comming from perl.
As an educational excersise I'm writing some code, which aims to change
the grub conf file menu.lst's default entry.
Consider the following code: (see code below)
If the new default entry line is longer than the original (e.g default 0,
changes to default 10, then one character of the next line is overwritten.
Is there a way of solving this progblem, without using a temp file?
Thx in advance
Jens
<code>
int alter_file(int timeout)
{
FILE *file;
regex_t *preg = malloc(sizeof(regex_t));
char *regex;
char *line;
line = (char*)malloc(sizeof(char)*257);
int ret;
regmatch_t* pmatch = (regmatch_t*)malloc(sizeof(regmatch_t));
size_t nmatch = 2;
regex = "^[[:blank:]]*default[[:blank:]]*([[:digit:]]*)";
ret = regcomp(preg,regex,REG_EXTENDED);
printf("ret %d",ret);
file = fopen("/boot/grub/menu.lst","r+");
if (file == NULL) { fprintf(stderr,"Couldn't open file for writing\n");
exit(1);}
while (fgets(line,256,file)!=NULL) {
ret = regexec(preg,line,nmatch,pmatch,0);
if (ret == 0) {
printf("end %d",pmatch[1].rm_eo+1);
fseek(file,(long)-(pmatch[1].rm_eo+1),SEEK_CUR);
fprintf(file,"%s","default 10\n");
}
}
return 0;
}
</code>