我正在尝试编辑文本文件中的一行,但在编辑文件时出现意外行为。我想要做的是调整看起来像的文本的特定行(点:100)。在函数中,我通过值传递要调整的新硬币和 ftell->user_point 文件的偏移量的参数。我得到的输出很奇怪。我尝试使用编辑的行将文件的其余部分复制到临时文件中,然后将其从我复制到临时文件的点复制回原始文件。(这是使用 ftell 的 user_point 偏移量)。这是带有类似条目的原始文件:
...
_______________________________________
nickname : geo
password : cuvctq
Name : george
Surname : papas
points : 100
participated :
past draws : 0
Chosen No. :
future draws : 0
Registered : Sun Feb 05 19:23:50 2012
...
第二次编辑运行后我得到的是:
...
_______________________________________
nickname : geo
password : cuvctq
Name : george
Surname : papaspoints : 98
participated :
past draws : 0
Chosen No. :
future draws : 0
Registered : Sun Feb 05 19:23:50 2012
...
At the end of the text i get one extra \n after i edit the
file whch is something i dont want :/
所以进一步的编辑会破坏文本......我还在行尾得到一个EXTRA \n,至少我认为是由于"r+"
模式,这是我也不想要的......
void coins_adjust(int coins_new,int user_point)
{
int lines,i,ln_point_copy;
char buffer[50],buff_copied[50];
FILE *lottary,*temp;
memset(buff_copied,'\0',sizeof(char)*50);
lottary=fopen("customers.txt","r");
temp=fopen("temp.txt","w");
fseek(lottary,user_point,SEEK_SET);
for (lines=0;lines<5;lines++)
{
memset(buffer,'\0',sizeof(char)*50);
if (lines==5)
ln_point_copy=ftell(lottary); //from TEMP to CUSTOMERS
fgets (buffer ,50 , lottary);
}
coins_new+=atoi(buffer+15);
strncpy(buff_copied,buffer,15); //copy 15 chars and fill with null
memset(buffer,'\0',sizeof(char)*50);
itoa (coins_new,buffer,10); //fix the new line to be entered
strcat(buff_copied,buffer); //the edited line is as it is supposed
strcat(buff_copied,"\n"); //to be with \n at the end.
puts(buff_copied);
printf("%s",buff_copied);fflush(stdout);
fprintf(temp,"%s",buff_copied);
for(i=getc(lottary); i!=EOF; i=getc(lottary)) //copy to temp
{
putc(i, temp);
}
fclose(lottary);
fclose(temp);
temp=fopen("temp.txt","r");
lottary=fopen("customers.txt","r+");
fseek(lottary,ln_point_copy,SEEK_SET);
for(i=getc(temp); i!=EOF; i=getc(temp)) //copy until eof
{
putc(i, lottary);
}
fclose(lottary);fclose(temp);
}
我已经调试了程序,一切似乎至少在传递给我存储行字符的数组的值上有效,但是\n
当我尝试将前一行复制回原始时,我不明白为什么它忽略了前一行。 . 在我复制回原始文件时,似乎有一个\r
我无法摆脱的字符......在此先感谢。