problems in saving to a text file

K

kimimaro

hi below is my save function that is used to placed data from the C program
to a text file for future usage.

void save()
{

FILE *save;
int i = 0;
save=fopen("employeerecord.txt", "a+");

do
{
if(strcmp(record.ID, "")!=0)
{
if(i!=0)
fprintf(save, "\n");
fprintf(save, "%s %s %s %s %s ", record.ID, record.Name,
record.Name2, record.Department[storage], record.Post[rank]);

}
else
{
break;
}
i++;
}while(i<500);
fclose(save);
}

There was no problem for me to save the first employee and the second but
when adding the 3rd employee data, this is what appears in the text file
:

1121 sonia cooling Management Maid 1121 sonia cooling Management Maid
1331 mustapha jamal Management Office_Boy 1121 sonia cooling Management
Maid
1121 sonia cooling Management Maid
1331 mustapha jamal Management Office_Boy
1111 cheng kahhin Administration Chief_Executive_Officer

Sonia is the 1st employee I add, mustapha second and cheng the third. My
data are ID firstname secondname department post and it seems the 1st and
second loops before going to the third pls help if the problem is in the
save function if not its in the add_function but I want to make sure if
its the save function
 
O

osmium

kimimaro said:
hi below is my save function that is used to placed data from the C
program
to a text file for future usage.

/* this function ..... */

replace the ellipses with ordinary English words telling what the function
is supposed to do.
Save what? A record? One record? Which one? Save all records, even if a
record has been saved recently?
My *guess* is the second one.
void save()
{

FILE *save;

Now you have a file named save and a function also named save. That's
confusing to a human. Try calling the file "fsave"
int i = 0;
save=fopen("employeerecord.txt", "a+");

do
{
if(strcmp(record.ID, "")!=0)
{
if(i!=0)
fprintf(save, "\n");


Note the human confusion. Is save a recursive call on the function, or the
name of a file? It's likely the word "recursive has no meaning to you. You
could look it up.
fprintf(save, "%s %s %s %s %s ", record.ID, record.Name,
record.Name2, record.Department[storage], record.Post[rank]);

}
else
{
break;
}
i++;
}while(i<500);
fclose(save);
}


<snip>
Your general approach is wrong. You should open the file *once* and close
it once for the entire program. You are heavily dependant on global
variables. If you want to save a particular record when you call save(),
you should give it a parameter telling it what, specifically to save. I
suggest a total rewrite. Even if you did get this to work it would be
hugely inefficient.
 
A

Al Bowers

kimimaro said:
hi below is my save function that is used to placed data from the C program
to a text file for future usage.

void save()
{

FILE *save;
int i = 0;
save=fopen("employeerecord.txt", "a+");

do
{
if(strcmp(record.ID, "")!=0)
{
if(i!=0)
fprintf(save, "\n");
fprintf(save, "%s %s %s %s %s ", record.ID, record.Name,
record.Name2, record.Department[storage], record.Post[rank]);

}
else
{
break;
}
i++;
}while(i<500);
fclose(save);
}

There was no problem for me to save the first employee and the second but
when adding the 3rd employee data, this is what appears in the text file
:

1121 sonia cooling Management Maid 1121 sonia cooling Management Maid
1331 mustapha jamal Management Office_Boy 1121 sonia cooling Management
Maid
1121 sonia cooling Management Maid
1331 mustapha jamal Management Office_Boy
1111 cheng kahhin Administration Chief_Executive_Officer

Sonia is the 1st employee I add, mustapha second and cheng the third. My
data are ID firstname secondname department post and it seems the 1st and
second loops before going to the third pls help if the problem is in the
save function if not its in the add_function but I want to make sure if
its the save function


yeah! Your function logic is flawed. You will first need to search
the entire file for a dupe. Then if none are found then you can
add the new record. Also, You may or may not wish to check for a dupe
name also. I would include that possibility in the functions I write.
For example, I would write two functions that does that you are
attempting with your function save. One function would search the
file for dupes. And another function that saves a record to the file.
Like:
if(!search_id(&emp,"employee.txt","1234")
add_record("employee.txt",&emp)
Where function search_id would prototype
int search_id(EMPLOYEE *p, const char *fname, const char *id))
p would be a pointer to storage for the data if a dupe is found, or
NULL if that information is unneccessary. fname would be the name of
the data file and id is the id string to be searched.

Compile and run the example code below. Function main will
read to records into the file. Run it and try to inter dupilcate
ids. The printout of the file will show that only one is added.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct EMPLOYEE
{
char id[50];
char name[50];
char gender[50];
char dept[50];
} EMPLOYEE;

char Dept[4][50] = {"Accounting", "Administration", "Management" ,
"Others"};
char Gender [2] [50] = {"Male", "Female"} ;

int add_record(const char *fname,EMPLOYEE *p);
void getstring(char *s, size_t sz);
int fget_employee(EMPLOYEE *p, FILE **fp);
void input_employee(EMPLOYEE *new);
void print_employee(EMPLOYEE *p);
size_t search_name(EMPLOYEE *p, const char *fname, const char *name);
size_t search_id(EMPLOYEE *p, const char *fname, const char *name);
int delete_record(const char *fname, size_t recnum);

int main(void)
{
EMPLOYEE emp;
const char *empfile = "employee.txt";
FILE *fp;

input_employee(&emp);
if(search_name(NULL,empfile,emp.name) ||
search_id(NULL,empfile,emp.id))
puts("n\Name or Id already exists.");
else add_record(empfile,&emp);
input_employee(&emp);

if(search_name(NULL,empfile,emp.name) ||
search_id(NULL,empfile,emp.id))
puts("\nName or Id already exists.");
else add_record(empfile,&emp);
fp = fopen(empfile,"r");
if(fp)
{
puts("\nThe array contents");
while(fget_employee(&emp,&fp))
print_employee(&emp);
}
else puts("Unable to open file");
return 0;
}

int add_record(const char *fname,EMPLOYEE *p)
{
FILE *fp;

if((fp = fopen(fname,"a")) == NULL) return 0;
fprintf(fp,"%s:%s:%s:%s\n",p->id,p->name,p->gender,p->dept);
fclose(fp);
return 1;
}

void getstring(char *s, size_t sz)
{
char *s1,*s2;
int ch;

fgets(s, sz,stdin);
if((s1 = strrchr(s,'\n')) != NULL) *s1 = '\0';
else while((ch = getchar()) != '\n');
for(s1 = s;(s2 = strchr(s1,':'));*s2 = '-',s1 = s2) ;
return;
}

int fget_employee(EMPLOYEE *p, FILE **fp)
{
char buf[256];

if(!fgets(buf, sizeof buf,*fp)) return 0;
if(4 != sscanf(buf,"%49[^:]:%49[^:]:%49[^:]:%49[^\n]",
p->id, p->name,p->gender,p->dept))
return 0;
return 1;
}

void input_employee(EMPLOYEE *new)
{
char buf[32];
int num;

printf("Enter employee ID: ");
fflush(stdout);
getstring(new->id,sizeof new->id);

printf("Enter employee Name: ");
fflush(stdout);
getstring(new->name,sizeof new->name);

do
{
printf("employee Gender\n\t1) %s\n"
"\t2) %s\nEnter Number: ",Gender[0],Gender[1]);
fflush(stdout);
getstring(buf,sizeof buf);
}while((num = atoi(buf)) < 1 || num > 2);
strcpy(new->gender,Gender[num-1]);

do
{
printf("employee Dept\n\t1) %s\n"
"\t2) %s\n\t3) %s\n\t4) %s\n"
"Enter Number: ",Dept[0],Dept[1],Dept[2],Dept[3]);
fflush(stdout);
getstring(buf,sizeof buf);
}while((num = atoi(buf)) < 1 || num > 4);
strcpy(new->dept,Dept[num-1]);
return;
}

void print_employee(EMPLOYEE *p)
{
if(p)
{
printf("\nid: %s\n"
"name: %s\n"
"gender: %s\n"
"dept: %s\n\n",
p->id,p->name,p->gender,p->dept);
}
return;
}

size_t search_name(EMPLOYEE *p, const char *fname, const char *name)
{
size_t counter,flag;
EMPLOYEE tmp;
FILE *fp;

if((fp = fopen(fname,"r")) == NULL) return 0;
for(counter = flag = 0; ;counter++ )
{
if(!fget_employee(&tmp,&fp)) break;
if(0 == strcmp(tmp.name,name))
{
counter++;
flag++;
break;
}
}
fclose(fp);
if(flag)
{
if(p) *p = tmp;
return counter;
}
return 0;
}

size_t search_id(EMPLOYEE *p, const char *fname, const char *id)
{
size_t counter,flag;
EMPLOYEE tmp;
FILE *fp;

if((fp = fopen(fname,"r")) == NULL) return 0;
for(counter = flag = 0; ;counter++ )
{
if(!fget_employee(&tmp,&fp)) break;
if(0 == strcmp(tmp.id,id))
{
counter++;
flag++;
break;
}
}
fclose(fp);
if(flag)
{
if(p) *p = tmp;
return counter;
}
return 0;
}

int delete_record(const char *fname, size_t recnum)
{
FILE *fpi;
size_t i,flag;
EMPLOYEE tmp;

if(!fname || !recnum) return 0;
if((fpi = fopen(fname,"r")) == NULL) return 0;
remove("tmp.txt");
for(i = 0;(fget_employee(&tmp, &fpi));i++)
{
if(i != (recnum - 1))
{
add_record("tmp.txt", &tmp);
flag++;
}
}
fclose(fpi);
remove(fname);
if(flag) rename("tmp.txt",fname);
return 1;
}
 
H

Herbert Rosenau

hi below is my save function that is used to placed data from the C program
to a text file for future usage.

void save()
{

FILE *save;
int i = 0;
save=fopen("employeerecord.txt", "a+");

do
{
if(strcmp(record.ID, "")!=0)
{
if(i!=0)
fprintf(save, "\n");
fprintf(save, "%s %s %s %s %s ", record.ID, record.Name,
record.Name2, record.Department[storage], record.Post[rank]);


What tries you to do here? Write all records - except the first one -
who have an epmty ID string?

Seems to be a bad logic.

Rething about you concept.
}
else
{
break;
}
i++;
}while(i<500);
fclose(save);
}

There was no problem for me to save the first employee and the second but
when adding the 3rd employee data, this is what appears in the text file
:

1121 sonia cooling Management Maid 1121 sonia cooling Management Maid
1331 mustapha jamal Management Office_Boy 1121 sonia cooling Management
Maid
1121 sonia cooling Management Maid
1331 mustapha jamal Management Office_Boy
1111 cheng kahhin Administration Chief_Executive_Officer

Sonia is the 1st employee I add, mustapha second and cheng the third. My
data are ID firstname secondname department post and it seems the 1st and
second loops before going to the third pls help if the problem is in the
save function if not its in the add_function but I want to make sure if
its the save function
This looks to be a bad design of your record structure. Something in
memory gets overwritten and as result the whole data structure gets
defektive even on disk.

Restart your design from scratch to fix all the bugs.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top