Can someone please help me with this....
Here's a sample.
Code:
#include <stdio.h>
#include <string.h>
#define MAX_PESSOA 128
#define MAX_TELE 37
#define QTD 3
#define MAX_TXT 128
typedef struct {
char name[MAX_PESSOA];
char phone[MAX_TELE];
int day;
int month;
int year;
int num[QTD]; // if the person has more than one phone number
char text[MAX_TXT];
} Person;
int writeacoupleofrecords(char *fname)
{
Person contacts;
FILE *writefile;
writefile=fopen(fname,"ab"); // Append records
if (!writefile)
return 1;
strcpy(contacts.name, "Bob S.");
strcpy(contacts.phone, "570-555-1212");
contacts.day = 24;
contacts.month = 12;
contacts.year = 2007;
contacts.num[0] = 1;
strcpy(contacts.text,"text1 message");
fwrite(&contacts,sizeof(Person),1,writefile);
strcpy(contacts.name, "Ted F.");
strcpy(contacts.phone, "570-555-1313");
contacts.day = 11;
contacts.month = 9;
contacts.year = 1989;
contacts.num[0] = 1;
strcpy(contacts.text,"text2 message");
fwrite(&contacts,sizeof(Person),1,writefile);
fclose(writefile);
return 0;
}
int readtherecords(char *fname)
{
FILE *readfile;
Person contacts;
readfile=fopen(fname,"rb");
if (!readfile)
return 1;
while(fread(&contacts, sizeof(Person),1, readfile) == 1)
{
printf("%s %s %02d %02d %d %d %s\n",
contacts.name,contacts.phone,contacts.day,contacts.month,contacts.year,contacts.num[0],contacts.text);
}
fclose(readfile);
return 0;
}
int main(void)
{
if(!writeacoupleofrecords("contacts.txt"))
readtherecords("contacts.txt");
else printf("writeacoupleofrecords failed\n");
return 0;
}