gpt4 book ai didi

c - fwrite写入不同数据(C编程)

转载 作者:行者123 更新时间:2023-11-30 16:56:20 25 4
gpt4 key购买 nike

简介

你好!这是一个小型 C 项目,保存用户的名字、姓氏并将其打印出来。

当您输入第一个用户时,它可以正常工作。

但是,当您添加另一个用户时,程序就会崩溃。


问题

  • 添加第二个用户时崩溃
<小时/>

问题

  • 当我添加第二个用户时,fwrite 是否将数据保存为两个不同的元素?

    例如:
    第一个用户:

    名字:John

    姓氏:Lemon

    第二个用户:< br/>
    名字:詹姆斯

    姓氏:邦德
<小时/>
  • 否则,如果没有,我如何将数据彼此分开?


任何帮助将不胜感激!谢谢!

#include<stdio.h>

char user[]={"user.txt"};

struct user
{
char firstname[10];
char lastname[10];
};

void viewdata ()
{
char input[20];

FILE *fp;

struct user u1;

fp = fopen(user,"rb");

fread(&u1,sizeof(u1),1,fp);

printf("Please enter user first name you wish to search: ");
scanf("%s",&input);

if ((strcmp(input,u1.firstname)==0))
{
printf("\nUser First Name: %s",u1.firstname);
printf("\nUser Last Name: %s\n\n",u1.lastname);
system("pause");
system("cls");
main();
}
else
printf("\nNot found!\n\n");
system("pause");
system("cls");
main();
};

void enterdata ()
{
char choice;

FILE *fp;

struct user u1;

printf("\nPlease enter first name: ");
scanf("%s",&u1.firstname);
fflush(stdin);

printf("\nPlease enter last name: ");
scanf("%s",&u1.lastname);
fflush(stdin);

printf("\nConfirm? (Y/N): ");
scanf("%c",&choice);
fflush(stdin);

if (choice == 'y' || choice == 'Y')
{
fp=fopen(user,"a");
fwrite(&u1,sizeof(u1),1,fp);
fclose(fp);
system("cls");
main();
}
else
printf("\nData has not been saved!");
system("pause");
main();
};

int main ()
{
int choice;

printf("\n1. Enter data\n");
printf("\n2. View data\n");

printf("\n\nPlease select an option: ");

scanf("%d",&choice);
fflush(stdin);

if (choice == 1)
{
system("cls");
enterdata();
}
else if (choice == 2);
{
system("cls");
viewdata();
}
}

最佳答案

If the file is successfully opened, the function returns a pointer to a FILE object that can be used to identify the stream on future operations. Otherwise, a null pointer is returned.

在调用 fopen() 后,您应该小心检查是否能够成功打开文件,方法是检查 fp == NULL ,如果是则出错。这将防止崩溃。

你的阅读方式也是错误的。如果您使用 fwrite,请确保使用 fread

fscanf(fp,"%s %s",&u1.名字,&u1.姓氏);//错误

尽管我强烈建议不要存储二进制数据并从文件中检索它们,但您应该这样做。

fread(&u1, sizeof(u1), 1, fp);

关于c - fwrite写入不同数据(C编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com