簡體   English   中英

從文件/在文件中用c讀取/寫入

[英]read/write with c from/in file

我想從文件中讀取內容,然后在文件中的字符上加上/減去用戶指定的數字。 用戶還將決定程序是要添加還是減去。 我的問題是,我無法在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;

}

您可以在同一循環中對同一文件使用fgetcfputc ,但必須記住,在調用fgetc ,文件指針位於下一個字符,以便fputc調用將覆蓋下一個字符,而不是僅覆蓋下一個字符。讀。 當然, fputc還將增加文件指針,使您每秒讀取和寫入一個字符。

如果要覆蓋剛剛讀取的字符,則必須使用fseek快退該位置。

我認為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.
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM