-4

尝试使用 fseek 修改名称,但它无法返回我想要的结果,即名称无法修改并保持不变

struct phonebook { char name[20]; };
struct phonebook a;

char temp[20];
cpPtr=fopen("name.txt","rb");//open the file
while(fread(&a,sizeof(a),1,cpPtr)==1){
    printf("Please enter name :\n");//require user to enter name
    scanf("%s",&temp);//temporary variable
    fflush(stdin);
    if(stricmp(a.name,temp)==0){
        printf("NAME :%s\n",a.name);
        else
            printf("The name is not exist");
        getch();
    }

    printf("Please enter new NAME :");
    scanf("&s",a.name);
    fflush(stdin);
    fseek(cpPtr,-sizeof(a),SEEK_CUR);//is there any wrong with seek?
    fwrite(&a,sizeof(a),1,cpPtr);
    fclose(cpPtr);
    printf("Name is modified");
    getch();
    system("cls");
}
4

1 回答 1

2

您打开文件只是为了阅读。如果要读写,则必须以读写模式打开文件。

fopen("name.txt","r+b"); // open read+write
于 2013-03-04T08:09:53.253 回答