【问题标题】:read/write with c from/in file用c从/在文件中读/写
【发布时间】:2013-01-11 02:39:03
【问题描述】:

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

代码如下:

#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;

}

【问题讨论】:

标签: c file


【解决方案1】:

您可以在同一个循环中对同一个文件使用fgetcfputc,但是您必须记住,在调用fgetc 之后,文件指针将定位在下一个字符上,以便fputc 调用将覆盖下一个字符,而不是刚刚读取的字符。当然fputc也会增加文件指针,引导你每隔一个字符读写一次。

如果你想覆盖你刚刚读到的字符,你必须使用fseek将位置倒退一步。

【讨论】:

    【解决方案2】:

    我认为 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.
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-09
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多