简体   繁体   中英

read/write with c from/in file

I want to read from a file and then add/substract to/from the characters that are in the file, a number given by the user. Also the user will decide if the program will add or subtract. My problem is, that I can't read and write the first character in the for loop. I read the first character, but I write at the end of what is already written in the file. I guess that I can't use fgetc and fputc in the same loop, or that I need to send *fp, back in the start of the file after the restart of the procedure (through a menu).

Here is the code:

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

}

You can use fgetc and fputc for the same file in the same loop, but you have to remember that after you called fgetc the file pointer is positioned at the next character so that the fputc call will write over the next character and not the one just read. Of course, fputc will also increase the file pointer, leading you to read and write every second character.

If you want to overwrite the character you just read, you have to use fseek to rewind the position one step.

I think fseek will work something like below:

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.
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM