Write records into file : c [duplicate] - c

This question already has answers here:
Using fflush(stdin)
(7 answers)
Closed 9 years ago.
int main()
{
FILE *fp;
char another = 'Y';
struct emp
{
char name[20];
int age;
float bs;
};
struct emp e;
fp = fopen("employee.dat", "w");
if(fp == NULL)
{
printf("file cannot be opened for writing\n");
exit(1);
}
while(another == 'Y')
{
printf("\n enter name, age and basic salary: ");
scanf("%s %d %f", e.name, &e.age, &e.bs);
fprintf(fp, "%s %d %f\n", e.name, e.age, e.bs);
printf(" Add another record (Y/N)");
fflush(stdin);
scanf("%c", &another);
}
fclose(fp);
return 0;
In this program I am trying to write records into file named, employee.dat. Program executed fine, but it will takes only one record of employee and then program gets terminated. It is not asking for next record to add i.e.,
fflush(stdin);
scanf("%c", &another);
are not getting executed in the program.
Thanks in advance....

The problem that you're experiencing is that scanf("%c", &another); only grabs a single character from the input buffer. This would be fine, except that there's still a newline left in the input buffer that resulted from hitting 'enter' after your input. You need to clear the input buffer after you use getchar() like this:
char c;
while ((c = getchar()) != '\n');

You can do this:
while(another == 'Y' || another == 'y')
{
printf("\n enter name, age and basic salary: ");
scanf("%s %d %f", e.name, &e.age, &e.bs);
fprintf(fp, "%s %d %f\n", e.name, e.age, e.bs);
printf(" Add another record (Y/N)");
another=getch();
//scanf("%c", &another);
}

You can fixed it simply by use : scanf("\n%c",&another); instead of scanf("%c",&another);
scanf("%s %d %f", e.name, &e.age, &e.bs);
Example--->Here your input is : name_1 22 6000.000 <"Enter">
Then in the buffer : name_1 -->e.name 22-->e.age 6000.00-->e.bs <"Enter">-->nothing
fflush(stdin);//it didn't delete the <"Enter">.
scanf("\n%c", &another);//here we deal with <"Enter">

Related

Why is specific line in text file not replaced but instead deleted?

I have this program where I can input the number of students, their names, and their corresponding grades for prelims, midterms, and finals. All of these user inputted data will be put on a text file.
I tried to create an edit function to update a specific line that contains a student's name and grades on the text file.
But instead of replacing it with newly updated data, it deletes it.
Here's my source code for the write function and getScore function, which will allow the user to input data (such as student name and grades) to the text file:
#define max 256
void write()
{
system("cls");
printf("\n Enter the number of students: ");
scanf("%d", &numberOfStudents);
FILE *fp;
fp = (fopen("studentRecord.txt", "a"));
if (fp == NULL)
{
printf("\n Error!");
exit(1);
}
fprintf(fp, " Name \t \t Prelims \t Midterms \t Finals \t Average \t Rating \n");
for (i = 0; i < numberOfStudents; ++i)
{
printf("\n Student No. %d ", i + 1);
getScore(studentName, &prelims, &midterms, &finals);
/******This is just another function for computing the average scores******/
averageScores = average(prelims, midterms, finals);
/******This is just also another function for rating the average scores******/
rating = rate(averageScores);
fprintf(fp, " %d.) %s \t %d \t \t %d \t \t %d \t \t %.2f \t \t %.2f \n", i + 1, studentName, prelims, midterms, finals, averageScores, rating);
}
fclose(fp);
printf("\n \n File studentRecord.txt is saved!");
getch();
view();
}
void getScore(char *studentName, int *prelims, int *midterms, int *finals)
{
printf("Name: ");
scanf("%s", studentName);
printf("\n \t Prelims: ");
scanf("%d", prelims);
printf("\n \t Midterms: ");
scanf("%d", midterms);
printf("\n \t Finals: ");
scanf("%d", finals);
}
Here's my source code for the edit function, which should allow the user to edit a specific line on the text file:
void edit()
{
system("cls");
FILE *fpo;
FILE *fp2;
int lno, linectr = 0;
char str[max];
char newln[max], temp[] = "temp.txt";
printf("\n Input the file to be opened: ");
fgets(file_name, max, stdin);
file_name[strlen(file_name) - 1] = '\0';
fpo = fopen(file_name, "r");
if (!fpo)
{
printf("\n Unable to open the input file!");
main();
}
fp2 = fopen(temp, "w");
if (!fp2)
{
printf("\n Unable to open a temporary file to write!");
fclose(fpo);
main();
}
printf("\n Input the line number you want to update: ");
scanf("%d", &lno);
printf("\n Student No. %d ", lno);
getScore(studentName, &prelims, &midterms, &finals);
averageScores = average(prelims, midterms, finals);
rating = rate(averageScores);
fprintf(fp, " %d.) %s \t %d \t \t %d \t \t %d \t \t %.2f \t \t %.2f \n", lno, studentName, prelims, midterms, finals, averageScores, rating);
lno++;
while (!feof(fpo))
{
strcpy(str, "\0");
fgets(str, max, fpo);
if (!feof(fpo))
{
linectr++;
if (linectr != lno)
{
fprintf(fp2, "%s", str);
}
else
{
fprintf(fp2, "%s", newln);
}
}
}
fclose(fpo);
fclose(fp2);
remove(file_name);
rename(temp, file_name);
getch();
view();
}
When compiled and run, it goes like this:
These are the user inputted data in the text file
And this is when I try to update line number 3's data
Lastly, this is when I try to view to updated contents of the text file that should've included the new data.
The line that should've been updated is rather deleted.
Please check my code if there's anything wrong with it. It would be a great help someone pointed out the error
The copying loop uses feof() to try and detect end of file, but this method is incorrect: you should just use the return value of fgets(), which will be a null pointer if no line could be read from the file.
while (fgets(str, max, fpo)) {
linectr++;
if (linectr == lno) {
fputs(newln, fp2);
} else {
fputs(str, fp2);
}
}
For further explanations, read Why is “while ( !feof (file) )” always wrong?
Note also that you should use snprintf instead of fprintf to compose the new line contents:
sprintf(newln, sizeof newln, " %d.) %s \t %d \t \t %d \t \t %d \t \t %.2f \t \t %.2f \n",
lno, studentName, prelims, midterms, finals, averageScores, rating);
The line number should not be updated either: remove the lno++; statement.

Infinite loop on printing in the file

We were asked to store values from one file to another. (Reading it from a source txt file and copying it into another txt file) I got all the syntax correct but somehow, my program's got a logical error in printing in the second file (Infinite loop so that's why it won't proceed in the next while loop.) The product of this program is getting the last set of information entered only and the loop never ends.
Here's my program:
char ans;
FILE *fp,*fp2;
fp = fopen("INVENTORY.txt","w");
do{
printf("Date (mm/dd/yy): ");
scanf("%d %d %d", &inv.dt.m, &inv.dt.d, &inv.dt.yr);
printf("Part No.: ");
scanf("%d", &inv.pno);
printf("Price: ");
scanf("%f", &inv.price);
printf("Quantity On Hand: ");
scanf("%d", &inv.qty);
printf("Reorder Parts: ");
scanf("%d", &inv.rp);
printf("Monthly Order: ");
scanf("%d", &inv.mo);
if(inv.qty < inv.rp)
inv.oa = (inv.rp + inv.mo) - inv.qty;
else
inv.oa = 0;
fprintf(fp,"%d/%d/%d\t%d\t%.2f\t%d\t%d\t%d\t%.2f\n", inv.dt.m, inv.dt.d, inv.dt.yr, inv.pno, inv.price, inv.qty, inv.rp, inv.mo, inv.oa);
printf("Add another (Y/N)? ");
scanf(" %c",&ans);
printf("\n");
}while(ans == 'Y' || ans == 'y');
fclose(fp);
fp = fopen("INVENTORY.txt", "r");
fp2 = fopen("REPORT.txt", "w");
while(fscanf(fp,"%d/%d/%d\t%d\t%.2f\t%d\t%d\t%d\t%.2f\n", &inv.dt.m, &inv.dt.d, &inv.dt.yr, &inv.pno, &inv.price, &inv.qty, &inv.rp, &inv.mo, &inv.oa)!=EOF){
fprintf(fp2,"%d\t%.2f\t%d\t%d\t%d\t%.2f\n", inv.pno, inv.price, inv.qty, inv.rp, inv.mo, inv.oa);
}
fclose(fp);
fclose(fp2);
fp2 = fopen("REPORT.txt","r");
printf("Part No.\tPrice\tQuantity On Hand\tReorder Parts\tMonthly Order\tOrder Amount");
while(fscanf(fp2,"%d\t%.2f\t%d\t%d\t%d\t%.2f\n", &inv.pno, &inv.price, &inv.qty, &inv.rp, &inv.mo, &inv.oa)!=EOF){
printf("%d\t%.2f\t%d\t%d\t%d\t%.2f",inv.pno, inv.price, inv.qty, inv.rp, inv.mo, inv.oa);
}
fclose(fp2);
return 0;
I hope someone can help me with this, thank you.
Joven,
I think your problem lies with scanf(" %c",&ans); try removing the space infront of "%c"
The best thing for you to do would to be put some output at the end of your loops for debugging, you have a lot of loops, at the end of each loop do something like printf("\nwhile loop id: 1, seq: %d\n", loop_count) you also have some things going on with your fclose and fopens, Accesing files takes a small bit of time, it's quicker for you to open the file when you need it, and then close it when your done...If you need to read and write to a file at the same time use fopen(filename, "rw").

Program cannot match datas in variables [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 6 years ago.
This is a part of my 'Phonebook' program.
void viewone(){
char name[25], fname[25];
int n, ncheck, op;
fp = fopen("Phonebook.txt","r");
printf ("\n Search by : \n 1: Name\n 2: Phone Number\n");
printf ("Enter option : ");
scanf ("%d",&op);
switch(op){
case 1:
printf ("\n Enter Name : ");
scanf ("%s",name);
fscanf(fp, "%s %d", fname, &ncheck);
while (!feof(fp)){
printf ("\n\n %s \n\n",fname);
if (fname == name){ \\ Problem in here
printf ("\n\n Contact Found...\n");
printf (" %s +880%d", fname, ncheck);
break;
}
else{
fscanf(fp, "%s %d", fname, &ncheck);
}
if (feof(fp)){
printf ("\n\n Contact Not Found...\n\n");
}
}
menu();
break;
case 2:
printf ("\n\n Enter Contact Number (+880) : ");
scanf ("%d",&n);
fscanf(fp, "%s %d", fname, &ncheck);
while (!feof(fp)){
if (ncheck == n){
printf ("\n\n Contact Found...\n");
printf (" %s +880%d\n", fname, ncheck);
break;
}
else{
fscanf(fp, "%s %d", fname, &ncheck);
}
if (feof(fp)){
printf ("\n\n Contact Not Found...\n\n");
}
}
menu();
break;
default:
printf ("\n Wrong option...\n\n");
viewone();
break;
}
}
When it comes to the marked line, the program should search the file for the 'fname' character until it matches the 'name' character. But though they match, nothing happens and the program still goes on. And in the end, it does what is told in the else statement. My question is why is this happening and how can i fix it?
My program runs perfectly when i search with phone number. But why is it not happening with character?
Comparing string is not done by ==. Instead use string compare function like this
strcmp(fname,name)

Linear search for an element within structures saved to file

I have a module which searches through a file to find an index, and if it's found it is supposed to print the details relevant to that index. The program compiles and runs, but no matter if the patient is saved or not, it prints that the patient is not found. What's the logic error I'm missing?
note:patientCount is a global variable which is written to another file and updated every time a patient is added.
void patientSearch(struct patientRec patient[], struct apptRec appt[])
{
system("cls");
int c=0;
char search[6], admit;
printf("Enter the patient ID of the patient you would like to search for.\n");
scanf("%i", &search);
fflush(stdin);
FILE *fp;
fp=fopen("patients.txt", "r");
if(fp==NULL)
{
printf("\nError opening file!");
}
else
{
for (c=0; c<patientCount; c++)
{
if (search==patient[c].patientID)
{
printf("\nPatient found.\n\n");
printf("Patient ID: %i", patient[c].patientID);
fscanf(fp, "%s", patient[c].fName);
printf("\nPatient First Name: ");
puts(patient[c].fName);
fscanf(fp, "%s", patient[c].sName);
printf("\nPatient Surname: ");
puts(patient[c].sName);
fscanf(fp, "%i %c", patient[c].age, patient[c].sex);
printf("\nPatient Age: %i\nPatient Sex: %c", patient[c].age, patient[c].sex);
fscanf(fp, "%s", patient[c].notes);
printf("\n\nNotes: \n");
puts(patient[c].notes);
}
else
{
fscanf(fp, "\n");
}
}
}
fclose(fp);
if (c==patientCount)
{
printf("\nThis patient does not exist. Would you like to admit this patient?\n1: Yes\n2: No\n");
scanf(" %c", &admit);
if (admit=='1')
{
admitPatient(patient, appt);
}
}
}
char search[6], admit;
scanf("%i", &search);
if (search==patient[c].patientID)
Either change to
int search; // This allows the rest of the code to match
or change to
char search[6], admit; //Change the rest of the code to match
scanf("%s", &search);
if (strcmp(search, patient[c].patientID) == 0)
printf("Patient ID: %s", patient[c].patientID);
To make your input and compare in the same format.
Make sure that your search array is big enough to include the final '\0'

Error when trying to store multiple information into text file

i'm trying to write a database to store information of staff. Here is my problematic code:
#include<stdio.h>
int main(){
char name[100], gender[100], email[100], id[10], phone[20];
FILE *fPtr;
fPtr=fopen("staffinfo.txt","w");
FILE *fPtr1;
fPtr1=fopen("staffinfo.txt","a+");
if (fPtr == NULL)
printf("Error in opening file\n");
if (fPtr1 == NULL)
printf("Error in opening file\n");
printf("\n===Add New Staff Profile===");
printf("\n\nPlease enter the following staff information.");
printf("\n\nStaff ID: ");
scanf("%s", &id);
fflush(stdin);
printf("Name\t: ");
fgets(name,100,stdin);
printf("Gender\t: ");
scanf("%s", &gender);
printf("Phone\t: ");
scanf("%s", &phone);
printf("Email\t: ");
scanf("%s", &email);
fprintf(fPtr, "Staff ID\t Name\t\t Gender\t\t Phone\t\t Email");
fprintf(fPtr1, "\n%s\t\t %s\t\t %s\t\t %s\t %s", id, name, gender, phone, email);
printf("\nSYSTEM: New Staff Profile is Added Successfully.");
fclose(fPtr);
fclose(fPtr1);
return 0;
}
The output give:
===Add New Staff Profile===
Please enter the following staff information.
Staff ID: 1
Name : Carmen Gray
Gender : Female
Phone : 123-4567890
Email : carmen#live.com
SYSTEM: New Staff Profile is Added Successfully.
--------------------------------
Process exited with return value 0
Press any key to continue . . .
However, the output in text.file is not as expected:
Staff ID Name Gender Phone Email
1 Carmen Gray
Female 123-4567890 carmen#live.com
The problem lies with this code:
fflush(stdin);
printf("Name\t: ");
fgets(name,100,stdin);
If I use scanf instead of fgets, I cannot store strings with spaces.
Can anyone suggest me how to make it work?
well, you have the whole string, you just need to put a null terminator on the end of the string or pass it to a new string:
int i = 0;
int lastPlace = 0;
for(i=0 ; i < 100 ; i++)
{
if(name[i] == '\n')
name[i] = '\0';
}
as zubergu said:
fgets Reads characters from stream and stores them as a C string into str until
(num-1) characters have been read or either a newline or the end-of-file is
reached, whichever happens first.
A newline character makes fgets stop reading, but it is considered a valid
character by the function and included in the string copied to str.
A terminating null character is automatically appended after the characters
copied to str.
this means the problem in your code is that you write the newline charecter to the file. just remove it!
full code:
#include<stdio.h>
int main(){
char name[100], gender[100], email[100], id[10], phone[20];
FILE *fPtr;
fPtr=fopen("staffinfo.txt","w");
FILE *fPtr1;
fPtr1=fopen("staffinfo.txt","a+");
if (fPtr == NULL)
printf("Error in opening file\n");
if (fPtr1 == NULL)
printf("Error in opening file\n");
printf("\n===Add New Staff Profile===");
printf("\n\nPlease enter the following staff information.");
printf("\n\nStaff ID: ");
scanf("%s", &id);
fflush(stdin);
printf("Name\t: ");
fgets(name,100,stdin);
// MY CODE EXAMPLE HERE
int k = 0;
int lastPlace = 0;
for(k=0 ; k < 100 ; k++)
{
if(name[k] == '\n')
name[k] = '\0';
}
printf("Gender\t: ");
scanf("%s", &gender);
printf("Phone\t: ");
scanf("%s", &phone);
printf("Email\t: ");
scanf("%s", &email);
fprintf(fPtr, "Staff ID\t Name\t\t Gender\t\t Phone\t\t Email");
fprintf(fPtr1, "\n%s\t\t %s\t\t %s\t\t %s\t %s", id, name, gender, phone, email);
printf("\nSYSTEM: New Staff Profile is Added Successfully.");
fclose(fPtr);
fclose(fPtr1);
return 0;
}
The problem is fgets reads '\n' and inputs it in your char array, and then puts '\0' at the end. So you basically include new line character to your string. What you have to do is to remove '\n', because it will be placed in your output file and mess up the results.

Resources