2013-01-10 208 views
0

我想从文件中读取数据,然后在文件中的字符(用户给出的数字)中添加/减去/从/中删除。此外,用户将决定程序是否添加或减少。我的问题是,我无法读写for循环中的第一个字符。我读了第一个字符,但是我在写入文件的末尾写入。我想我不能在同一个循环中使用fgetc和fputc,或者我需要在程序重新启动后(通过菜单)发回* fp,重新开始。用c从/中读取/写入文件

下面是代码:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
char str[50],keystr[50],*p,c; 
FILE *fp; 
int i,k,key,buff1,buff2,choice; 

start: 

printf("Make a choice\n1.Add\n2.Sub\n3.Exit\n"); 
scanf("%d",&choice); 
if(choice==3) goto end; 
getchar(); 
printf("\nGimme the key"); 
fgets(keystr,50,stdin); 

key=0; 
i=0; 

while(keystr[i]) 
{ 
    key=key+keystr[i]; 
    i++; 
} 
printf("\n%d",key); 
printf("\nDwste onoma arxeiou"); 
fgets(str,50,stdin); 

fp=fopen(str,"r+"); 
if (fp==NULL) printf("error"); 
buff1=0; 
buff2=0; 
for(;;) 
{ 
    if((c=fgetc(fp))==EOF) break; 
    buff1=c; 
    if(choice==1) 
    { 
      buff1=buff1+key; 
      c=buff1; 
      fputc(c,fp); 
      printf("\n%d",buff1); 
    } 
    else if(choice==2) 
    { 
      buff1=buff1-key; 
      c=buff1; 
      fputc(c,fp); 
      printf("\n%d",buff1); 
    } 
} 
goto start; 
end: 
fclose(fp); 
printf("\nBye"); 
    return 0; 

}

+1

这里好奇 - 为什么要用'goto'而不是函数调用?我听说过“意大利面代码”,但从来没有见过它的实施,并被教导永远不要这样做。 – ChiefTwoPencils

+0

@ C.Lang同意。 goto is famous evil –

+0

如果((c = fgetc(fp))== EOF)break,我认为你可以使用fseek类似 –

回答

2

您可以使用fgetcfputc在同一回路相同的文件,但你要记住,你叫fgetc后文件指针定位在下一个字符处,以便fputc调用将写入下一个字符而不是刚刚读取的字符。当然,fputc也会增加文件指针,导致你读写第二个字符。

如果您想覆盖您刚刚阅读的字符,您必须使用fseek来倒退一步。

1

我认为FSEEK将工作类似如下:

int opr =0; 
for (;;) 
{ 
fseek(fp,opr,SEEK_SET) 
if((c=fgetc(fp))==EOF) break; 
buff1=c; 
if(choice==1) 
{ 
     buff1=buff1+key; 
     c=buff1; 
     fseek(fp,opr,SEEK_SET); 
     fputc(c,fp); 
     printf("\n%d",buff1); 
     opr++: 
} 
else 
{ 
.... //Similarly for else loop. 
} 
} 
+0

fseek中的opr是什么? – alex777