int main() {
scanf("%d",&a);
while(1) {
switch(a) {
case 0:
exit(0);
case 1:
fp = fopen("info.txt", "r");
if (fp == NULL)
printf("File doest not exist! \n");
else {
for(i=0; !feof(fp); i++) {
fscanf(fp, "%s %s %s %s %s %s",
user[i].name,
user[i].surname,
user[i].gender,
user[i].status,
user[i].education,
user[i].adress);
printf("%s, %s, %s, %s, %s, %s\n",
user[i].name,
user[i].surname,
user[i].gender,
user[i].status,
user[i].education,
user[i].adress);
fclose(fp);
}
}
break;
case 2:
for(i=0; i<N; i++) {
printf("\nUser application data\n", i+1);
printf("Name: ");
gets(user[i].name);
gets(user[i].name);
printf("Surname: ");
gets(user[i].surname);
printf("Gender: ");
gets(user[i].gender);
printf("Status: ");
gets(user[i].status);
printf("Education: ");
gets(user[i].education);
printf("Adress: ");
gets(user[i].adress);
fp = fopen("info.txt", "a");
fprintf(fp, "\n%s %s %s %s %s %s",
user[i].name,
user[i].surname,
user[i].gender,
user[i].status,
user[i].education,
user[i].adress);
fclose(fp);
}
}
}
}
Ok, so I'm kinda lost right now. Case 2 where I add strings to text file works flawlessly, but when when I want to check out the added data to the text file using the case 1, program crashes, so far Ive tried several things and no improvements. Would be very thankful for some help!
In case 1: you are fclose-ing every time you loop which means that after the first loop it will close the file then when it tries to feof and fscanf in the next loop the program will fail.
Related
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.
I am facing an issue with the last part of the assignment. I want to update(modify) the specific value in a text file but this program stop working from the if statement in the while loop. I have tried to fix this issue but I couldn't figure it out. Please help.
int Equant()
{
DisplayList();
FILE * fpr_r = fopen("donation.txt", "r");
FILE * fpr_w = fopen("Edonation.txt", "w");
if (fpr_r == NULL || fpr_w == NULL)
{
printf ("An able to open the file for writing");
exit(1);
}
int Inumber, v=0;
double NQuant, NVQuant;
struct Donate Esearch;
printf ("\nEnter the ID you want to change the quantity: ");
scanf ("%d", &Inumber);
while (fread(&Esearch, sizeof(struct Donate),1,fpr_r))
{
fscanf (fpr_r,"%d %s %s %s %d %lf,", &Esearch.IDd, &Esearch.supply, &Esearch.Scode, &Esearch.Cdonator, &Esearch.Nship, &Esearch.QuantityR);
if (Esearch.IDd == Inumber)
{
printf ("ID: %d Name of Supply: %s, Supply Code: %s, Donator: %s, No. of Shipment: %d, Quantity Received (Million): %lf\n",
Esearch.IDd, Esearch.supply, Esearch.Scode, Esearch.Cdonator, Esearch.Nship, Esearch.QuantityR);
printf ("\nEnter the new Quantity value: ");
scanf ("%lf", &NVQuant);
Esearch.QuantityR = NVQuant;
}
fwrite (&Esearch, sizeof(struct Donate),1,fpr_w);
}
fclose(fpr_r);
fclose(fpr_w);
if (!v)
{
printf ("No line founded.\n");
}
I need to write a C program to fetch data from one file and write it to another file, without using user defined functions. My requirements are to:
Search customer details by Name.
Store the transaction data (paid amount) in another text file.
I did the code to search by name. But its not working,
#include <stdio.h>
#include <stdlib.h>
int main () {
char name[10], nic[10], mobile[10];
char fname[10], fnic[10], fmobile[10];
char choice;
int amount;
FILE *cfptr;
printf("Enter search type - \n 1. NAME \n 2. NIC \n 3.MOBILE \n ----> ");
scanf("%c", &choice);
printf("Enter search text : ");
scanf("%s", &name);
cfptr = fopen ("customer.dat", "r");
while (!feof(cfptr)){
fscanf(cfptr, "%s %s %s", fname, fnic, fmobile);
printf("Read Name |%s|\n", fname );
printf("Read NIC |%s|\n", fnic );
printf("Read Mobile |%s|\n", fmobile );
}
fclose(cfptr);
scanf("%d", &amount);
return(0);
}
customer.dat File
Shan 100012 200202
Marsh 121213 667675
Kim 126573 663412
This code is not complete asI cant filter the single name assigning
if(name == fname)
as am getting
assignment to expression with array type error
Can any one complete me the code to search and save to another file so I can do the amount calculation part?
int Search_in_File(char *fname, char *str) {
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[512];
//gcc users
//if((fp = fopen(fname, "r")) == NULL) {
// return(-1);
//}
//Visual Studio users
if((fopen_s(&fp, fname, "r")) != NULL) {
return(-1);
}
while(fgets(temp, 512, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", temp);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
//Close the file if still open.
if(fp) {
fclose(fp);
}
return(0);
}
few comments:
when scanning the choice, read it as an integer and not as a character.
scanf("%c", &choice); // change to scanf("%d", &choice);
single '=' is an assigment, you meant comparison which is double '=='
if(name = fname) // comparison is if(name == fname)
in order to compare string, do not use '==' operator. use strcmp or implement an equivalent of strcmp.
Thanks for the effort, As with changes, I have changed my code as below and its working. Without checking with the name, I alternately checked with the nic.
#include <stdio.h>
int main(void){
int nic, n, mobile;
char name[30];
FILE *aPtr;
aPtr = fopen("Details.txt","w");
if(aPtr == NULL){
printf("File cannot be opened");
return -1;
}
printf("Enter nic to search - ");
scanf("%d", &n);
fscanf(aPtr, "%d %-s %d", &nic, name, &mobile);
while(!feof(aPtr)){
if(nic == n){
Printf("%d %s %d \n", nic, name, mobile);
}
fscanf(aPtr, "%d %s %d", &nic, name, &mobile);
}
fclose(aPtr);
return 0;
}
Case study 8 – Develop a Hospital Management System Write C programs to
Store the patient details in to a text file.
View the details of patients using phone number, NIC , etc…
Store the patient channeling details to another text file.
Display the summary of the patients.
create 4 seperate c programs covering all sections.
Can someone please help me because I don't get an output for section 2 and 4. section 1 and 3 works fine. All for sections are interconnected I guess.
**This is the code I created for section 1:
#include<stdio.h>
int main(void)
{
int pnum,age,cnum,nic;
char name[20],gender[6],address[50];
FILE * fp;
fp = fopen("patient.txt", "a");
printf("Add patient details\n\n");
printf("Patient number: ");
scanf("%d", &pnum);
printf("First name: ");
scanf(" %s", &name);
printf("Gender: ");
scanf(" %s", &gender);
printf("Age: ");
scanf("%d", &age);
printf("Address: ");
scanf(" %s", &address);
printf("NIC: ");
scanf("%d", &nic);
printf("Contact number: ");
scanf("%d", &cnum);
fprintf(fp, "%d %s %s %d %s %d %d\n", pnum, name, gender, age, address, nic, cnum);
fclose(fp);
return 0;
}
**This is the code I created for section 2:
#include<stdio.h>
int main(void)
{
int pnum,age,cnum,nic;
char name[20],gender[6],address[50];
FILE * fp;
fp = fopen("patient.txt", "r");
if ( fp != NULL)
{
while(!feof(fp))
{
fscanf(fp, "%d %s %s %d %s %d %d", pnum, name, gender, age, address, nic, cnum);
printf("%d %s %s %d %s %d %d", pnum, name, gender, age, address, nic, cnum);
}
fclose(fp);
}
else
{
printf("could not open file\n");
}
return 0;
}
**This is the code for section 3:
#include <stdio.h>
int main(void)
{
int pnum,chnum,nic;
char name[20],doc[20],sickness[50];
FILE * fp1;
fp1 = fopen("channeling.txt", "a");
printf("Add patient channeling details\n\n");
printf("Patient number: ");
scanf("%d", &pnum);
printf("Channeling number: ");
scanf("%d", &chnum);
printf("First name: ");
scanf(" %s", &name);
printf("NIC: ");
scanf("%d", &nic);
printf("Sickness: ");
scanf(" %s", &sickness);
printf("Prescribed doctor: ");
scanf(" %s", &doc);
fprintf(fp1, " %d %d %s %d %s %s\n", pnum, chnum, name, nic, sickness, doc);
fclose(fp1);
return 0;
}
**This is the code for section 4:
#include<stdio.h>
int main(void)
{
int pnum,age,cnum,nic;
char name[20],gender[6],address[50];
FILE * fp;
fp = fopen("patient.txt", "r");
if ( fp != NULL)
{
while(!feof(fp))
{
fscanf(fp, "%d %s %s %d %s %d %d", pnum, name, gender, age, address, nic, cnum);
printf("%d %s %s %d %s %d %d", pnum, name, gender, age, address, nic, cnum);
}
fclose(fp);
}
else
{
printf("could not open file\n");
}
return 0;
}
Problems are:
while (!feof(fp) feof indicates an error has occurred. So the logic in your program is not correct. (if fscanf does get an error, printf will still get executed)
Forgot & in fscanf.
I am writing a program in C that reads file data (name, answer of q1, q2, q3) from the user, and store the data in a .txt file, and allow the user to view the data they have entered. Currently, I have difficulty with the function that allows data to see the last record.
Here is my code:
struct pre_survey{
char name[20];
int q1;
int q2;
int q3;
};
struct pre_survey temp;
struct pre_survey get;
int main(){
while (pre_or_post!=0){
if(pre_or_post==1){
printf("\n1. append(enter) data\n");
printf("2. check first record\n");
printf("3. check last record\n");
printf("please select your choice\n");
scanf("%d", &choice);
switch (choice){
case 1: append();
break;
case 2: frst_record();
break;
case 3: last_record();
break;}}
void append(){
fp=fopen("pre-survey.txt", "a");
printf("name\n");
scanf("%s", &temp.name);
printf("q1:\n");
scanf("%d", &temp.q1);
printf("q2:\n");
scanf("%d", &temp.q2);
printf("q3:\n");
scanf("%d", &temp. q3);
fprintf(fp, "%s %d %d %d", temp.name, temp.q1, temp.q2, temp.q3);
fclose(fp);}
void last_record(){
fp=fopen("pre-survey.txt", "r");
fseek(fp, -sizeof(temp),SEEK_END);
fscanf(fp, "%s %d %d %d", get.name, &get.q1, &get.q2, &get.q3);
printf("name: %s\n", get.name);
printf("q1: %d\n", get.q1);
printf("q2: %d\n", get.q2);
printf("q3:%d\n", get.q3);
fclose(fp);
}
Right now, when I try to find the last record, the data for the first record shows up. I think the problem is that when I check the sizeof(temp) is 32, and when I use
fp=fopen("pre-survey.txt", "r");
fseek(fp,0, 2);
size=ftell(fp);
printf("size:%d\n", size);
to check the size of the whole file, it is 34.
So when I am reading from the end of the file by size of temp, it goes to the first record.
But I am not sure what I did wrong in the code.
If the position to read the record by fseek,
Record must be a fixed length.
E.g.
void append(void){
FILE *fp=fopen("pre-survey.txt", "a");
printf("name\n");
scanf("%19s", temp.name);
printf("q1:\n");
scanf("%d", &temp.q1);
printf("q2:\n");
scanf("%d", &temp.q2);
printf("q3:\n");
scanf("%d", &temp. q3);
//32bit system MAX_INT : 2147483647 (10digits)
//19char 2digit 2digit 2digit\n total:30 (windows:31(\n->CRLF)
fprintf(fp, "%-20s%3d%3d%3d\n", temp.name, temp.q1, temp.q2, temp.q3);
fclose(fp);
}
void last_record(void){
FILE *fp=fopen("pre-survey.txt", "rb");
//fseek(fp, -31, SEEK_END);//for windows
fseek(fp, -30, SEEK_END);
fscanf(fp, "%s %d %d %d", get.name, &get.q1, &get.q2, &get.q3);
printf("name: %s\n", get.name);
printf("q1: %d\n", get.q1);
printf("q2: %d\n", get.q2);
printf("q3: %d\n", get.q3);
fclose(fp);
}