sugar sugar - 2 months ago 14
C Question

fwrite to write different data (C Programming)

Introduction

Hello! This is a small C project that saves the user's first name, last name and prints it out.

It would work without problems when you enter the first user.

However, when you add another user, the program crashes.


Problem



  • crashes when you add a second user






Questions


  • does
    fwrite
    save data as two different elements when I add a second user?

    For example:
    First User:

    First Name: John

    Last Name: Lemon

    Second User:

    First Name: James

    Last Name: Bond







  • Else if it doesn't, how do I separate the data's from each other?




Any help would be greatly appreciated! Thank you!

#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",u1.lastname);
}
};

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();
}
}

Answer

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.

You should take care to check whether you were able to open the file successfully once you call fopen() by checking fp == NULL and erroring out if so. This will prevent the crash.

You're also reading it the wrong way. If you use fwrite, make sure to use fread.

fscanf(fp,"%s %s",&u1.firstname,&u1.lastname); // wrong

Although I strongly advise on not storing binary data and retrieving them from a file, you should be doing something like this instead.

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