我试图编辑文本文件中的一行,但在编辑文件时出现意外的行为。我想要做的是调整看起来像一个文本的特定线(点:100)。在函数中,我通过值传递参数来调整新的硬币,并用ftell-> user_point将文件偏移。我得到的输出是奇怪的。我尝试将文件的其余部分复制到临时文件中,并将其复制到一行,然后将它复制回原始文件,并将其复制到临时文件中(即用户点的偏移量为ftell)。 原来这里是外商投资企业有这样的条目:使用临时文件在文本文件中编辑行C
...
_______________________________________
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
字符,我无法摆脱,而我复制回原来的... 在此先感谢。
为什么不一次一行地阅读,如果它包含你想改变的东西然后改变它,并且把这一行写出到新文件中。然后,要更改的行的实际位置可以在任何位置,并且如果文件的格式发生更改,则不必担心程序。 – 2012-02-06 10:44:51
@JoachimPileborg其实这就是我所做的或多或少的,但这些条目可以是数百等。所以我需要编辑线,并将其放置在它的位置。 – BugShotGG 2012-02-06 11:01:30