Write data in files from array of structures using pointers - c

I am trying to rewrite text in files, changing first line by +1(that holds number of struct saved in igraci.txt) This part is working fine. Then rewrite all text that was there before(This is also working fine) and in the end add 2 new lines in text. Problem is in the last code i wrote here
These are some global variables that I am having problem with and strcture
int RijeciBroj = 0;
int IgraciBroj = 0;
typedef struct Igrac
{
char ime[20];
int brojPoena;
};
This is method for allocating memmory for structures having in mind that one strcture is going to be added
struct Igrac* napraviProstor(int n) {
IgraciBroj = n; //here I try to give global new value
printf("U NAPRAVI PROSTOR : %d", IgraciBroj); // Here i get -9282928
return (struct Igrac*) malloc((n + 1) * sizeof(struct Igrac));
}
This is method that is reading text from file and storing it in allocated memory
void ucitajIgrace(struct Igrac *arr) {
static const char filename[] = "igraci.txt";
FILE *file;
file = fopen(filename, "r");
if (file != NULL)
{
char line[20];
int n;
fscanf(file, "%d", &n);
int i = -1;
int k = 0;
fgets(line, 20, file);
while (fgets(line, 20, file) != NULL) /* read a line */
{
line[strcspn(line, "\n")] = '\0';
i++;
if (i == 0) {
strcpy((arr + k)->ime, line);
}
if (i == 1) {
(arr + k)->brojPoena = atol(line);
k++;
i = -1;
}
}
printf("Igraca: %d", IgraciBroj); //here i get -9892827280
fclose(file);
}
else
{
perror(filename);
}
}
Main method
int main()
{
int o;
Igrac *igr;
FILE *file1;
file1 = fopen("igraci.txt", "r");
if (file1 != NULL)
{
char line[20];
fscanf(file1, "%d", &o); //first line is number of structs
igr = napraviProstor(o);
ucitajIgrace(igr);
}
pocniIgru(rijeci,igr); //ignore rijeci that is another array that is working perfect and has nothing to do with my problem
return 0;
}
This is method where I have problem
void pocniIgru(char** rijeci, struct Igrac *igraci) {
int dobijeni[5] = {}; //array that is saving random numbers so they don't repeat
int brojac1 = 0; //used for index of dobijeni[5]
char srpska[30]; // for user input
char ime[20]; //for users name that we are going to store in igraci.txt
int poeni = 0; //number of points
bool moze; //boolean for loop control
printf("Pocinje igra\n");
printf("\n\n\n\n");
int pitanje; // for random number that we are going to get
for (int i = 0; i < 5; i++) {
moze = true;
LOOP:do {
srand(time(NULL));
pitanje = rand() % RijeciBroj-1; //random number between 0 - global variable here global variable is working fine!
if (pitanje % 2 != 0) {
pitanje++; // I need even number and 0 is accepted
}
for (int k = 0; k < 5; k++) {
if (dobijeni[k] == pitanje) { //checking if we arleay had that number
goto LOOP; // goto LOOP if we had that number so we pick another
}
}
dobijeni[brojac1] = pitanje; //storing that number in loop for later check so it won't repeat
moze = false; // do-while stops
brojac1++;
} while (moze);
printf("Engleska rijec je: %s", rijeci[pitanje]); //get word from array
printf("Unesite rijec na srpskom jeziku: ");
scanf("%30s", srpska); //user input for comparing
strtok(rijeci[pitanje + 1], "\n"); //we need to remove newline
if (strcmp(rijeci[pitanje+1], srpska) == 0) { //cheking if next word is same with user input
poeni += 2;
printf("Tacno! Vas broj peona je %d\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", poeni);
}
else {
poeni -= 1;
if (brojac != 5) {
printf("Greska! Vas broj peona je %d\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", poeni);
}
}
}
printf("Ukupan broj poena je: %d\n", poeni);
printf("Unesite svoje ime: "); //Enter your name
scanf("%s", ime); //get name
if (strcmp(ime, "")) { //check if it's empty
IgraciBroj += 1; //global variable +1 for rewriting in file
strcpy((igraci + IgraciBroj)->ime, ime); //save name in char* struct in last place that is empty
(igraci + IgraciBroj)->brojPoena = poeni; //save points in char* struct in last place that is empty
printf("%s osvojili ste %d poena", (igraci + IgraciBroj)->ime, (igraci + IgraciBroj)->brojPoena); //Here i get normal result and name
FILE *file1;
file1 = fopen("igraci.txt", "w");
if (file1 != NULL)
{
fprintf(file1, "%d\n", IgraciBroj);
for (int broj = 0; broj < IgraciBroj; broj++) {
fprintf(file1, "%s\n", (igraci + broj)->ime); //Problem !! I get some lines before name in file example(----------Name)
fprintf(file1, "%d\n", (igraci + broj)->brojPoena); //Problem !! I get some number like -9899887
}
}
}

Related

fscanf not reading from a file containing asterisk characters

I tried to read a file containing an empty box of '*', the error message doesn't get printed, so the file is opened, but the scan doesn't work. I tried to print the count variable, and the value of count is 0. I don't really know where the fault is. Please help... Thanks
the file content that I want to read
int openmap(int file_no){
char filename[32];
char mapp[100][100];
int number;
int count;
int x[100];
int nomor = 1;
for(int i = 1; i <= file_no; i++){
sprintf(filename, "map%d.txt", i);
FILE *test = fopen(filename,"r");
if(test)
{
printf("%2d. Map %d\n", nomor, i);
x[nomor-1] = i;
nomor++;
fclose(test);
}else if(!test && i > file_no){
printf("No map available!");
return 1;
}
}
do{
printf("[0 to cancel] [1 - %d]>> ", nomor-1);
scanf("%d", &number);
}while(number < 0 || number > file_no);
if(number > 0){
sprintf(filename,"map%d.txt", x[number-1]);
printf("%s", filename);
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(int i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
}
I created a small test program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main () {
char mapp[100][100];
int i, count = 0;
char filename[32];
sprintf(filename, "test.txt");
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof(open)){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
as far as i can see the only issue you have regarding the relevant section is your while loop condition, you should use: while(!feof(open)) - i tested my solution and it works so it seems that this is the only issue in your solution

Creating a program in C that saves and shows data

I'm new with C, and on the university they are making us create a program that can save data introduced by the user, read the data and check if it’s well introduced. After that it must save that data in each free space, you have 10 empty spaces for saving the data. With all the data saved it must show also the data and compare it with all the data introduced. I made the part of reading the data introduced and cheking if its ok. The problem that I have is that I don’t know how I could make the data base and show that data. Here is the code that I have till now.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[30];
int num_sample;
char section;
int cabin;
int day;
int month;
int year;
}Species;
int menu() {
int op = 0;
printf ("\nPrototype Nature Reserve.\n");
printf ("1. Insert a new species.\n");
printf ("2. List the species housed.\n");
printf ("3. Show stadistics.\n");
printf ("4. Exit.\n");
printf ("\nIntroduce an option: ");
scanf ("%d", &op);
return op;
}
void New_species() {
Species e;
int i, j;
char species[100];
char aux[10];
printf("Enter data:\n");
//A fflush is made to not have a problem with the number entered in the menu
fflush(stdin);
gets (species);
//While it is different from - read the text
for (i = 0; species[i] != '-'; i++) {
e.name[i] = species[i];
}
e.name[i] = '\0';
i++;
//We add 1 to the position i because is ending in - and should start reading from the following
for (j = 0; species[i] != '-'; i++,j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.num_sample = My_atoi(aux);
// Check that the sample is a number and not a character
if (e.num_sample <= 0 || e.num_sample >= 100) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the day introduced
for (j = 0; species[i] != '/'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.day = My_atoi(aux);
//Controls the format of the day
if (e.day <= 0 || e.day > 31) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the month introduced
for (j = 0; species[i] != '/'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.month = My_atoi(aux);
//Controls the format of the month
if (e.month <= 0 || e.month > 12) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the year introduced
for (j = 0; species[i] != '-'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.year = My_atoi(aux);
//Controls the format of the year
if (e.year < 1970 || e.year > 2060) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the section introduced
e.section = species[i];
//Controls that the section is in capital letters
if (e.section < 'A' || e.section > 'Z') {
printf ("--> Error in data format.\n");
}
i+= 2;
//As the cabin is at the end it must reach the \0
for (j = 0; species[i] != '\0'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.cabin = My_atoi(aux);
if (e.cabin < 0 || e.cabin > 20) {
printf ("--> Error in data format.\n");
}
printf ("Species stored successfully (%d/10 free).");
//This printf is just to ensure that the data entered was read correctly
printf ("\n%s", species);
}
int My_atoi(char cad[10]) {
int r = 0;
int i;
for (i = 0; cad[i] != '\0'; i++) {
r = r * 10;
r += cad[i] - '0';
}
return r;
}
void list_species() {
}
void stadistics() {
}
void executeOption(int op) {
switch (op) {
case 1:
New_species();
break;
case 2:
list_species();
break;
case 3:
stadistics();
break;
default:
break;
}
}
int main() {
int op = 0;
do {
op = menu();
executeOption(op);
} while (op != 4);
return 0;
}
I’ve seen that you can use files* so it can create a .txt file for storing but I don’t know how to use it and I don't think that it's allowed in this program.
I'll leave a photo of how it should work
Thanks.
ok u need to save data to a file and load from a file.
here a short code of my and read and write:
#include<stdio.h>
#include<stdlib.h>
typedef struct worker
{
int sal;
char name[25];
}W;
void main()
{
FILE *f;
int i,j=4;
W a[3];
while(j!=3)
{
printf("\nEnter\n[1]write\n[2]read\n[3]exit\n");
scanf("%d",&j);
if(j==1)
{
if (f==NULL)
{
printf("Error!!\n");
exit(0);
}
f=fopen("workers.txt","w");
for(i=0;i<3;i++)
{
printf("\nEnter worker name: ");
scanf("%s",&a[i].name);
printf("\nEnter worker sal: ");
scanf("%d",&a[i].sal);
fprintf(f,"%s %d",a[i].name,a[i].sal);
}
if(j==2)
{
if (f==NULL)
{
printf("Error!!\n");
exit(0);
}
f=fopen("workers.txt","r");
for(i=0;i<3;i++)
{
fscanf(f,"%s %d",a[i].name,&a[i].sal);
printf("\n%s %d",a[i].name,a[i].sal);
}
}
}
fclose(f);}
and I don't think that it's allowed in this program
why wouldn't you be allowed? Yes indeed you can go through two alternatives
To text file
This is the one proposed by dor in his answer where he shows you the way of writing text through fprintf.
To binary file
You can also write to a file using fwrite/fseek like this example I found surfing around you can check it out here -> c-tutorial-binary-file-io
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
my_record.x= counter;
fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile);
}
fclose(ptr_myfile);
return 0;
}
and retrieving back the data from the binary may go this way as the tutorial shows
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
If you are looking for a solution in a .txt file I have a proposal,
#include <stdio.h>
int main(){
FILE *in;
FILE *OUT = fopen("read_at.txt", "w");
char name[20];
char capture[80];
int age = 0;
float grade = 0;
puts("introduce your name:");
scanf("%19s", name);
puts("introduce your age:");
scanf("%i", &age);
puts("introduce your Math grade(0-10):");
scanf("%f", &grade);
fprintf(OUT, "Age %i, Grade %f, Name %s\r\n", age, grade, name);
fclose(OUT);
if(!(in = fopen("read_at.txt","r"))){
fprintf(stderr, "The file could not be opened. \n");
return 1;
}
while (fscanf(in, "Age %i, Grade %f, Name %20[^\n]\n", &age, &grade, name)==3){
printf("A %i years old student has achieved a %f mark in last math exam, that student is: %s", age,grade, name);
}
fclose(in);
}
In this code that I have just created you can see how you can just create one file and read and get its data if it has a concrete format. If you are looking for a database you can just put values separated by “;” and new lines (\n). With that if you save it as .csv you would obtain an excel sheet and quite a good database.
If you are interested in this solution, just let me know if you need any additional help.
Regards,

How to return an array from a specific function?

I have been working on this function for the past two days and I cant seem to figure it out. The function displayBoard() opens up a text file, in this case "board.txt" and places it into a 1D array. The code was provided by my professor. I made it into a function and tried to return the array board[] so I can manipulate it in main but I am unable to do it, What am I missing?
void displayBoard ()
{
FILE *pInputFile; // file pointer
char board[64]; // the 8x8 board
int i=0; // loop counter
char inputFileName[] = "board.txt";
// Associate the actual file name with file pointer and try to open it
pInputFile = fopen(inputFileName, "r");
// Verify input file was found
if (pInputFile == NULL) {
printf("Attempt to open file %s failed. Exiting ... \n", inputFileName);
exit( -1);
}
// Read from the file into the board. Space in front of %c is important!
while (fscanf(pInputFile, " %c", &board[i]) != EOF) {
i++;
}
fclose(pInputFile); // close input file
// show contents of board
printf("Board is: ");
for (i=0; i<64; i++) {
if (i%8 == 0) {
printf("\n");
}
printf("%c ", board[ i]);
}
printf("\n\n");
return board;
}
int main ()
{
printf(" %s", board); // This is my printf statement to see if I am able to access
// board[] from the function
}
You need to make the method return a char * by declaring the function
char * displayBoard {
...
}
You can not. You have to pass the array you want to modify using pointers and modify it inside the function.
#include <stdio.h>
void function(int b[][10], int m, int n){
int i = 0, j = 0;
for(i = 0; i < m; ++i){
for(j = 0; j < n; ++j){
b[i][j] = i + j;
}
}
}
int main(){
int board[10][10] = {0};
int i = 0, j = 0;
for(i = 0; i < 10; ++i){
for(j = 0; j < 10; ++j){
printf("%d ", board[i][j]);
}
printf("\n");
}
function(board, 10, 10);
for(i = 0; i < 10; ++i){
for(j = 0; j < 10; ++j){
printf("%d ", board[i][j]);
}
printf("\n");
}
return 0;
}
Ok I decided to part my function into 2, one to generate the board and one to to display the board, so I can just use displayBoard() whenever I want to re-display it in main.
void generateBoard (char board[]){
FILE *pInputFile; // file pointer
int i=0; // loop counter
char inputFileName[] = "board.txt";
// Associate the actual file name with file pointer and try to open it
pInputFile = fopen(inputFileName, "r");
// Verify input file was found
if( pInputFile == NULL) {
printf("Attempt to open file %s failed. Exiting ... \n", inputFileName);
exit( -1);
}
// Read from the file into the board. Space in front of %c is important!
while( fscanf(pInputFile, " %c", &board[ i]) != EOF) {
i++;
}
fclose( pInputFile); // close input file
}
void displayBoard (char board[]){
// show contents of board
printf("Board is: ");
int i;
for( i=0; i<64; i++) {
if( i%8 == 0) {
printf("\n");
}
printf("%c ", board[ i]);
}
printf("\n\n");
}
I have an update on my function, I am a first time user of this site so im not sure if I should be posting it here or on my OP. This is what I came up with
char* displayBoard (char board[]){
FILE *pInputFile; // file pointer
int i=0; // loop counter
char inputFileName[] = "board.txt";
// Associate the actual file name with file pointer and try to open it
pInputFile = fopen(inputFileName, "r");
// Verify input file was found
if( pInputFile == NULL) {
printf("Attempt to open file %s failed. Exiting ... \n", inputFileName);
exit( -1);
}
// Read from the file into the board. Space in front of %c is important!
while( fscanf(pInputFile, " %c", &board[ i]) != EOF) {
i++;
}
fclose( pInputFile); // close input file
// show contents of board
printf("Board is: ");
for( i=0; i<64; i++) {
if( i%8 == 0) {
printf("\n");
}
printf("%c ", board[ i]);
}
printf("\n\n");
return board;
}
When you write code returning results in an array, it is better to let the caller provide the array in which the code should return its results than to let the code allocate itself an array.
The reason for this is that pointer ownership transfers make it hard to reason about memory management, so it is better to keep their amount at a minimum.

runtime error when trying to read data from file

I have a question on logical error, the error was
"Run-Time Check Failure #2 - Stack around the variable 'list' was corrupted."
there are a total of 60 lines in the in.txt file
this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE_NAME 20
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)
typedef struct
{
char *name;
int score;
}RECORD;
int main (void)
{
// Declarations
FILE *fp;
char fileName[FILE_NAME];
RECORD list[LIST_SIZE];
char buffer[100];
int count = 0;
int i;
// Statements
printf("Enter the file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if(fp == NULL)
printf("Error cannot open the file!\n");
while(fgets(buffer, 100, fp) != NULL)
{
list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*));
if(count > 50)
{
}
if( count < 50)
{
sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
for( i =1; i < (50 - count); i++)
{
list[count + i].name = 0;
list[count + i].score = 0;
}
}
count++;
}
printf("Read in %d data records\n", count);
fclose(fp);
return 0;
}
in this program I' m trying to read data from file to array of structures, so if the number of data is less than 50, structures that don't have data will be zero out and if the number of data is more than 50 the program will only read the first 50 structures.
how can i fix the runtime error?
Perhaps...
while(fgets(buffer, 100, fp) != NULL)
{
if( count >= 50)
{
break;
}
if( count < 50)
{
list[count].name = (char*) malloc(strlen(buffer)*sizeof(char));
sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
count++;
}
}
for( i =0; i < (50 - count); i++)
{
list[count + i].name = 0;
list[count + i].score = 0;
}
What if count = 50?
Try with the following in your while loop bringing if block in the start or at the end;
if(count >= 50) //count should be checked for >= 50 before being used.
{
}
list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*)); //list size is 50 so list[50] won't work. out of bound.

Task using .txt file and phonebook program in C

Below is my code for a phonebook program in C. I'm having trouble modifying it. I need to modify it so that after adding entries to the phonebook , the contents will be written to a .txt file. After deleting an entry I need the contents to be written to the same .txt file and have the entire contents printed. Am I supposed to use the fopen () function? I'm a beginner...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Phonebook_Contacts
{
char FirstName[20];
char LastName[20];
char PhoneNumber[20];
} phone;
void AddEntry(phone * );
void DeleteEntry(phone * );
void PrintEntry(phone * );
void SearchForNumber(phone * );
void RandomName(phone * );
void DeleteAll(phone * );
void FreeContacts (phone * );
int counter = 0;
char FileName[256];
FILE *pRead;
FILE *pWrite;
int main (void)
{
phone *phonebook;
phonebook = (phone*) malloc(sizeof(phone)*100);
int iSelection = 0;
if (phonebook == NULL)
{
printf("Out of Memory. The program will now exit");
return 1;
}
else {}
do
{
printf("\n\t\t\tPhonebook Menu");
printf("\n\n\t(1)\tAdd Friend");
printf("\n\t(2)\tDelete Friend");
printf("\n\t(3)\tDisplay Phonebook Entries");
printf("\n\t(4)\tSearch for Phone Number");
printf("\n\t(5)\tFind a Random Friend");
printf("\n\t(6)\tDelete All Entries");
printf("\n\t(7)\tExit Phonebook");
printf("\n\nWhat would you like to do? ");
scanf("%d", &iSelection);
if (iSelection == 1)
{
AddEntry(phonebook);
}
if (iSelection == 2)
{
DeleteEntry(phonebook);
}
if (iSelection == 3)
{
PrintEntry(phonebook);
}
if (iSelection == 4)
{
SearchForNumber(phonebook);
}
if (iSelection == 5)
{
RandomName(phonebook);
}
if (iSelection == 6)
{
DeleteAll(phonebook);
}
if (iSelection == 7)
{
printf("\nYou have chosen to exit the Phonebook.\n");
system("pause");
FreeContacts(phonebook);
return 0;
}
} while (iSelection <= 9);
}
void AddEntry (phone * phonebook)
{
pWrite = fopen("phonebook_contacts.dat", "a");
if ( pWrite == NULL )
{
perror("The following error occurred ");
exit(EXIT_FAILURE);
}
else
{
counter++;
realloc(phonebook, sizeof(phone));
printf("\nFirst Name: ");
scanf("%s", phonebook[counter-1].FirstName);
printf("Last Name: ");
scanf("%s", phonebook[counter-1].LastName);
printf("Phone Number (XXX-XXX-XXXX): ");
scanf("%s", phonebook[counter-1].PhoneNumber);
printf("\n\tFriend successfully added to Phonebook\n");
fprintf(pWrite, "%s\t%s\t%s\n", phonebook[counter-1].FirstName, phonebook[counter-1].LastName, phonebook[counter-1].PhoneNumber);
fclose(pWrite);
}
}
void DeleteEntry (phone * phonebook)
{
int x = 0;
int i = 0;
char deleteFirstName[20]; //
char deleteLastName[20];
printf("\nFirst name: ");
scanf("%s", deleteFirstName);
printf("Last name: ");
scanf("%s", deleteLastName);
for (x = 0; x < counter; x++)
{
if (strcmp(deleteFirstName, phonebook[x].FirstName) == 0)
{
if (strcmp(deleteLastName, phonebook[x].LastName) == 0)
{
for ( i = x; i < counter - 1; i++ )
{
strcpy(phonebook[i].FirstName, phonebook[i+1].FirstName);
strcpy(phonebook[i].LastName, phonebook[i+1].LastName);
strcpy(phonebook[i].PhoneNumber, phonebook[i+1].PhoneNumber);
}
printf("Record deleted from the phonebook.\n\n");
--counter;
return;
}
}
}
printf("That contact was not found, please try again.");
}
void PrintEntry (phone * phonebook)
{
int x = 0;
printf("\nPhonebook Entries:\n\n ");
pRead = fopen("phonebook_contacts.dat", "r");
if ( pRead == NULL)
{
perror("The following error occurred: ");
exit(EXIT_FAILURE);
}
else
{
for( x = 0; x < counter; x++)
{
printf("\n(%d)\n", x+1);
printf("Name: %s %s\n", phonebook[x].FirstName, phonebook[x].LastName);
printf("Number: %s\n", phonebook[x].PhoneNumber);
}
}
fclose(pRead);
}
void SortByFirstName (phone * phonebook)
{
int i = 0;
int x = 0;
int swap;
int TempCounter = counter;
phone Temp;
do
{
swap = 0;
for(i = 1; i < TempCounter; i++)
{
if(strcmp(phonebook[i-1].FirstName, phonebook[i].FirstName) > 0)
{
Temp = phonebook[i];
phonebook[i] = phonebook[i-1];
phonebook[i-1] = Temp;
strcpy(Temp.FirstName, phonebook[i].FirstName);
strcpy(Temp.LastName, phonebook[i].LastName);
strcpy(Temp.PhoneNumber, phonebook[i].PhoneNumber);
swap = 1;
}
}
TempCounter--;
} while (swap);
printf("\nYour friends in Alphabetical Order by First Name:\n\n");
for( x = 0; x < counter; x++ )
{
printf("\n(%d)\n", x+1);
printf("Name: %s %s\n", phonebook[x].FirstName, phonebook[x].LastName);
printf("Number: %s\n", phonebook[x].PhoneNumber);
}
}
void SortByLastName (phone * phonebook)
{
int i = 0;
int x = 0;
int swap;
int TempCounter = counter;
phone Temp;
do
{
swap = 0;
for(i = 1; i < TempCounter; i++)
{
if(strcmp(phonebook[i-1].LastName, phonebook[i].LastName) > 0)
{
Temp = phonebook[i];
phonebook[i] = phonebook[i-1];
phonebook[i-1] = Temp;
strcpy(Temp.FirstName, phonebook[i].FirstName);
strcpy(Temp.LastName, phonebook[i].LastName);
strcpy(Temp.PhoneNumber, phonebook[i].PhoneNumber);
swap = 1;
}
}
TempCounter--;
} while (swap);
printf("\nYour friends in Alphabetical Order by First Name:\n\n");
for( x = 0; x < counter; x++ )
{
printf("\n(%d)\n", x+1);
printf("Name: %s %s\n", phonebook[x].FirstName, phonebook[x].LastName);
printf("Number: %s\n", phonebook[x].PhoneNumber);
}
}
void SearchForNumber (phone * phonebook)
{
int x = 0;
char TempFirstName[20];
char TempLastName[20];
printf("\nPlease type the name of the friend you wish to find a number for.");
printf("\n\nFirst Name: ");
scanf("%s", TempFirstName);
printf("Last Name: ");
scanf("%s", TempLastName);
for (x = 0; x < counter; x++)
{
if (strcmp(TempFirstName, phonebook[x].FirstName) == 0)
{
if (strcmp(TempLastName, phonebook[x].LastName) == 0)
{
printf("\n%s %s's phone number is %s\n", phonebook[x].FirstName, phonebook[x].LastName, phonebook[x].PhoneNumber);
}
}
}
}
void RandomName (phone * phonebook)
{
int iRandom = 0;
srand(time(NULL));
iRandom = rand() % counter;
int x = iRandom;
printf("\nYour random friend is: %s %s\n", phonebook[x].FirstName, phonebook[x].LastName);
printf("Their phone number is: %s\n", phonebook[x].PhoneNumber);
}
void DeleteAll (phone * phonebook)
{
int x = 0;
char nullStr[20] = {'\0'};
for ( x = 0; x < counter; x++ )
{
strcpy(phonebook[x].FirstName, nullStr);
strcpy(phonebook[x].LastName, nullStr);
strcpy(phonebook[x].PhoneNumber, nullStr);
--counter;
}
printf("All Contacts have been deleted.\n");
}
void FreeContacts (phone * phonebook)
{
--counter;
for ( ; counter > 0; --counter)
{
free(phonebook[counter].FirstName);
free(phonebook[counter].LastName);
free(phonebook[counter].PhoneNumber);
free(phonebook);
counter = 0;
return;
}
}
Are you sure you want to be doing "realloc(phonebook, sizeof(phone));" in your AddEntry() function? That's almost certainly not doing what you think it is.
Pretty much all the code you need is already here in this program. I would recommend you start by looking up tutorials or reading the file I/O chapter of books. An additional resource for you is the man pages for the C functions. If you're on a *NIX system you can type man fopen or you can type that into Google to get the same results on a windows system.
Here's the man page for fopen(). As you can see there are two parameters, the name of the file you want to open and the mode.
Clearly there are options to open a file for writing there as well as appending a file that already exists.
You mentioned a requirement to write to a .txt file, in your code you're opening a .dat file phonebook_contacts.dat is this the file you were talking about?
One of the easiest options is to read the entire file into memory then change it there and write it back to the file (over write the existing file), but it's not efficent as you'll have to loop over each existing element and copy them into you phonebook variable. You might want to check with your instructor to see if this is an acceptable solution. Something like:
while( more to read){
read fname line
strcpy(phonebook[i].first_name, fname)
read lname line
strcpy(phonebook[i].last_name, fname)
read num line
strcpy(phonebook[i].number, num)
increment i
}

Resources