473,657 Members | 2,451 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problems in saving to a text file

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("emp loyeerecord.txt ", "a+");

do
{
if(strcmp(recor d[i].ID, "")!=0)
{
if(i!=0)
fprintf(save, "\n");
fprintf(save, "%s %s %s %s %s ", record[i].ID, record[i].Name,
record[i].Name2, record[i].Department[storage], record[i].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

Nov 14 '05 #1
3 2292
"kimimaro" writes:
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("emp loyeerecord.txt ", "a+");

do
{
if(strcmp(recor d[i].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[i].ID, record[i].Name,
record[i].Name2, record[i].Department[storage], record[i].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.

Nov 14 '05 #2


kimimaro wrote:
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("emp loyeerecord.txt ", "a+");

do
{
if(strcmp(recor d[i].ID, "")!=0)
{
if(i!=0)
fprintf(save, "\n");
fprintf(save, "%s %s %s %s %s ", record[i].ID, record[i].Name,
record[i].Name2, record[i].Department[storage], record[i].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.t xt","1234")
add_record("emp loyee.txt",&emp )
Where function search_id would prototype
int search_id(EMPLO YEE *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(cons t char *fname,EMPLOYEE *p);
void getstring(char *s, size_t sz);
int fget_employee(E MPLOYEE *p, FILE **fp);
void input_employee( EMPLOYEE *new);
void print_employee( EMPLOYEE *p);
size_t search_name(EMP LOYEE *p, const char *fname, const char *name);
size_t search_id(EMPLO YEE *p, const char *fname, const char *name);
int delete_record(c onst char *fname, size_t recnum);

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

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

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

int add_record(cons t 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(E MPLOYEE *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("employe e Gender\n\t1) %s\n"
"\t2) %s\nEnter Number: ",Gender[0],Gender[1]);
fflush(stdout);
getstring(buf,s izeof buf);
}while((num = atoi(buf)) < 1 || num > 2);
strcpy(new->gender,Gende r[num-1]);

do
{
printf("employe e 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,s izeof 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(EMP LOYEE *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_employ ee(&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(EMPLO YEE *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_employ ee(&tmp,&fp)) break;
if(0 == strcmp(tmp.id,i d))
{
counter++;
flag++;
break;
}
}
fclose(fp);
if(flag)
{
if(p) *p = tmp;
return counter;
}
return 0;
}

int delete_record(c onst 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_employe e(&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;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #3
On Sat, 30 Oct 2004 15:48:15 UTC, "kimimaro"
<li************ @yahoo.com> wrote:
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("emp loyeerecord.txt ", "a+");

do
{
if(strcmp(recor d[i].ID, "")!=0)
{
if(i!=0)
fprintf(save, "\n");
fprintf(save, "%s %s %s %s %s ", record[i].ID, record[i].Name,
record[i].Name2, record[i].Department[storage], record[i].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.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3706
by: deko | last post by:
I've been trying to use the Access Import Wizard to expedite importing data into my mdb. The nice thing about the wizard is that I can import from different file formats - txt, xls, even Outlook - and dump everything into a table. The problem is once I have the data imported into a new table, I can't do much with it. If I try to run an Append query and insert data from the new table into an existing table, the query fails - "Error...
1
1337
by: David Johnston | last post by:
I am converting to the .NET platform and I am starting with C#. Just for exercise I'm writing a text editor and I am having some problems with saving files. I am using a single document interface system. I am just working with plain text now but I was wondering what differences I would have to make to save between .txt, .rtf, or even .doc if possible. Thanks for any help you could give or examples you could point me to . Thanks again.
4
3287
by: dale zhang | last post by:
Hi, I am trying to save and read an image from MS Access DB based on the following article: http://www.vbdotnetheaven.com/Code/Sept2003/2175.asp Right now, I saved images without any errors. After reading the ole object from db, I saved it to C: as file1.bmp and displayed on the web. But it can not be displayed. After I manually sent the file to wordpad, it shows
1
1730
by: Ruy Castelli | last post by:
I created a ASP.NET page using C# and I'm using two components to access a MS-Access database, which are: - oleDbConnection - oleDataAdapter The MS-Access database is in the correct directory (IIS has permission to read/write) and everything seems ok, but IIS says that it can't open the file because there is someone else using it exclusively (impossible, I'm using a stand alone computer and I closed everything) or I need permission
1
8124
by: Duffman | last post by:
Hi, I have what seems to be a common problem, but the solutions I've found don't seem to work. I would like to use a web service to create a file at a UNC location in a shared file. Currently I'm just running it locally and saving the file locally using my machines UNC path. I have given user ASPNET full control over the folder I want to write the file to. I've also tried using the web config identity impersonation to use my user...
18
3784
by: TORQUE | last post by:
Hi, Im wondering if anyone can help me with a problem. I have a form with more than 50 unbound fields. Some of the fields will be blank from time to time. This seems to be where im having trouble. I have tried keeping some of the fields bound and when I use the save button it has been saving as 2 different records. This is unacceptable. This is what I have, can anyone help me out with this?
10
2084
by: connyledin | last post by:
Im trying to create a version of the game Wumpus. Mine is called Belzebub. But im STUCK! And its due tuesday 2 maj. Im panicing! Can some one help me?? here is the file: http://esnips.com/webfolder/b71bfe95-d363-4dd3-bfad-39999a9e36d0 What i have the biggest problems with now is between line 8 and 23. How i can move the character trough the game. Other parts of the game that have with the movement to do is between line 83-114 and...
5
2256
by: samadams_2006 | last post by:
I'm having a problem in accessing a Microsoft Access Database in a VB.NET Web Application. It's so straight forward, I thought I'd walk you through all the details here: 1) I have a .NET Web Application called "Lesson18b" under "C:\Inetpub\wwwroot\Lesson18b". 2) I have one Web Form on this Lesson called "Form18b.aspx" 3) In this same Folder under Inetpub I have the Microsoft NorthWinds
3
7072
by: MIUSS | last post by:
Hello everyone! I got a problem with creating new line... I tried this: lstrcpy(NewLineIdr, TEXT("\r\n")); I already tried this: NewLineIdr = 0x000D; NewLineIdr = 0x000A; NewLineIdr = 0x0000; I need it to use it in my saving procedure because I need to create tabullary text file. But my effort usually results in one or two small
6
2369
by: Juha S. | last post by:
Hi, I'm writing a small text editor type application with Python 2.5 and Tkinter. I'm using the Tk text widget for input and output, and the problem is that when I try to save its contents to a .txt file, any Scandinavian letters such as "äöå ÄÖÅ" are saved incorrectly and show up as a mess when I open the .txt file in Windows Notepad. It seems that the characters will only get mixed if the user has typed them into the widget, but if...
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8823
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8726
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7320
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1944
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1604
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.