My program is to ask the user to enter the name and age of the person in his group. The number of person is not known to the user in the beginning of the program. The user keeps on entering the data till the user enters the age zero. The program finally prints the average age.
The source code is below
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct group {
char user_Name[21];
int user_age;
}Group;
int main()
{
Group *REC1;
FILE *out_file, *read_file;
int count_age=0, age, sum_age, i;
float avg_age;
char name[21]="", str[21]= "details.txt";
char sample_chr;
//opening a file in writing mode
out_file = fopen(str, "a");
// test for files not existing.
if (out_file == NULL)
{
printf("Error! Could not open file\n");
exit(-1); // must include stdlib.h
}
printf("\nEnter the Details of the person:\n\n");
do
{
printf("Enter the User Name:\n");
fflush(stdin);
scanf("%[^\n]",name);
printf("Enter the Age:\n");
fflush(stdin);
scanf("%d",&age);
if(age == 0)
{
break;
}
else
{
// write to file
fprintf(out_file,"%s,%d\n", name, age);
}
}while(1);
read_file = fopen(str,"r");
//counting the number of lines present in the above file
sample_chr = getc(read_file);
while (sample_chr != EOF)
{
if (sample_chr == '\n')
count_age = count_age +1;
sample_chr = getc(read_file);
}
rewind(read_file);
//allocating space for array of structure dynamically
printf("\n%d\n",count_age);
count_age = count_age - 1;
REC1 = (Group*)malloc(count_age*sizeof(Group));
//storing the values in array of structures
for(i=0; i<=count_age; i++)
fscanf(read_file, "%s,%d", REC1[i].user_Name, &REC1[i].user_age);
fclose(read_file);
fclose(out_file);
for(i =0; i<=count_age; i++)
printf("\n%s %d\n", REC1[i].user_Name, REC1[i].user_age);
for(i=0, sum_age=0; i<=count_age; i++)
sum_age = sum_age + REC1[i].user_age;
avg_age = (float)sum_age/(count_age);
printf("\n\nThe average age is %f\n\n\n", avg_age);
system("pause");
return 0;
}
while i am compiling it doesn't shows any error. When i am running it shows exe file stopped working.
the following is working
there had to be changed the format in scanf() of name[] ( http://www.cplusplus.com/reference/cstdio/scanf/ )
, the fclose(out_file) had to be moved and the ending condition of the while loop had to be changed ...
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct group {
char user_Name[21];
int user_age;
}Group;
int main()
{
Group *REC1;
FILE *out_file, *read_file;
int count_age=0, age, sum_age, i;
float avg_age;
char name[21]="", str[21]= "details.txt";
char sample_chr;
//opening a file in writing mode
out_file = fopen(str, "w");
// test for files not existing.
if (out_file == NULL)
{
printf("Error! Could not open file\n");
exit(-1); // must include stdlib.h
}
printf("\nEnter the Details of the person:\n\n");
do
{
printf("Enter the User Name:\n");
scanf("%21s[^\n]",name);
printf("Enter the Age:\n");
scanf("%d",&age);
if(age == 0)
{
break;
}
else
{
// write to file
fprintf(out_file,"%s , %d \n", name, age);
}
}while(age != 0);
fclose(out_file);
read_file = fopen(str,"r");
//counting the number of lines present in the above file
sample_chr = getc(read_file);
while (sample_chr != EOF)
{
if (sample_chr == '\n')
count_age = count_age +1;
sample_chr = getc(read_file);
}
rewind(read_file);
//allocating space for array of structure dynamically
printf("\n Number of group members : %d \n",count_age);
count_age = count_age - 1;
REC1 = (Group*)malloc(count_age*sizeof(Group));
//storing the values in array of structures
for(i=0; i<=count_age; i++)
fscanf(read_file, "%s , %d", REC1[i].user_Name, &REC1[i].user_age);
fclose(read_file);
for(i =0; i<=count_age; i++)
printf("\n Name : %s Age : %d \n", REC1[i].user_Name, REC1[i].user_age);
for(i=0, sum_age=0; i<=count_age; i++)
sum_age = sum_age + REC1[i].user_age;
avg_age = (float)sum_age/(count_age);
printf("\n\nThe average age is %f\n\n\n", avg_age);
return 0;
}
Related
so for one of my classes, I have to create a .txt file in c and then delete a few lines off of it. I wrote a separate function for each of these operations.
the creation function goes smoothly either way but the delete function only works after I separately create the file AND THEN delete while the the creation function is turned into a comment (aka it only works when I delete lines off a file that was already created before execution)
is there a way to make them both work at the same time?
ps: idk if this is an obvious question for a non-beginner
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 256
typedef struct a
{
int quan, num, price;
char name[100];
} ar;
ar art;
void ajt(int n)
{
int i;
FILE *f = fopen("stock.txt", "w");
if (f == NULL)
return;
for (i = 1; i <= n; i++)
{
printf("name of the product n* %d: ", i);
scanf("%s", &art.name);
fprintf(f, "name of the product n* %d is: %s ", i, art.name);
printf("number of the product n* %d: ", i);
scanf("%d", &art.num);
fprintf(f, "number of the product n* %d is: %d ", i, art.num);
printf("quantity of the product n* %d: ", i);
scanf("%d", &art.quan);
fprintf(f, "quantity of the product n* %d is: %d ", i, art.quan);
printf("price of the product n* %d:", i);
scanf("%d", &art.price);
fprintf(f, "price of the product n* %d is: %d \n", i, art.price);
printf("\n\n");
}
}
void del()
{
FILE *fileptr1, *fileptr2;
char filename[40];
char ch;
int delete_line, temp = 1;
printf("the name of your file: ");
scanf("%s", filename);
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
rewind(fileptr1);
printf("which product do u want to delete? ");
scanf("%d", &delete_line);
fileptr2 = fopen("copy.c", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == '\n')
temp++;
if (temp != delete_line)
{
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
rename("copy.c", filename);
printf("\n the text file after modifications:\n");
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
}
int main()
{
int n;
printf("how many products: ");
scanf("%d", &n);
printf("\n\n");
ajt(n);
del();
}
Either close the file after creating it or call fflush(f); to flush the stream buffer to the file system. If you do not do that, data remains in memory in the process; it is not written to the file system. So the file does not contain the data yet, so opening a separate stream to it cannot read or change that data.
I am trying to give an if statement to check if a particular name is present in text file, then give access to it otherwise give error message.
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("For person details, please enter the person name: \n");
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
int catch, i=0, index=0;
char ch[100];
printf("Enter your Name: ");
if (scanf("%s", )){ // Don't know what to put here?
perror("Error while reading!");
return 0;
}
catch = fgetc(fr);
while(catch != EOF){
ch[index] = catch;
if (ch[index] == ' '){
ch[index] = '\0';
printf("Here is your result: %s\n",ch);
index = 0;
i++;
}
else
index++;
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
Simply the program firstly opens a file and asks for a user input and verifies if the provided content is case-sensitively matched with the file. If so, then it'll let the program access the entire file and display on the screen, to do that, we must use another FILE b/c the old *fp is already manipulated and in case it's reused, it may display wrong data.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("file.txt", "r"); // for verification
FILE *fp1 = fopen("file.txt", "r"); // for future use
char ch[50], str[50];
short int FLAG = 0;
printf("Enter the string: ");
scanf("%s", &str); // asks for input
while (fscanf(fp, "%s", ch) != EOF) {
if (!strcmp(ch, str)) { // checks if a string matches provided by the user
printf("Found! Here's your details...\n\n");
FLAG = 1;
}
}
if (!FLAG == 1) { // no? exits.
printf("Not found, access denied!\n");
return -1;
}
fclose(fp);
int c = fgetc(fp1); // yes? let's go...
while (c != EOF) {
printf("%c", c); // displays containing data
c = fgetc(fp1);
}
fclose(fp1);
return 0;
}
You'll want to add a variable for your scanf output:
char name[100];
if (scanf("%s", name) != -1)
// ...
Then to compare both you'll use strcmp.
#include <string.h>
//...
if (strcmp(ch, name) == 0)
// both are equal
Note that you can access documentation for scanf and strcmp by typing man scanf or man strcmp in your terminal.
int main()
{
printf("For person details, please enter the person name and id card
number: \n");
printf("Enter your Name: ");
char personName[100];
scanf("%s", personName);
printf("Enter your card number: ");
int cardNumber;
if (scanf("%d", &cardNumber)){
printf("no error detected");
}
else{
printf("error while reading");
}
return 0;
}
The fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
printf("For person details, please enter the person name: \n");
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
int catch, i = 0, index = 0;
char ch[100] = { 0 };
if (fr == NULL)
{
perror("Invalid file opening!");
return 1;
}
printf("Enter your Name: ");
fgets(ch, 100, fr);
size_t len = strcspn(ch, "\n");
ch[(len < 100) ? (len) : (99)] = 0; // For file safety checking
if (strlen(ch)) { // Don't know what to put here?
perror("Error while reading!");
return 1;
}
catch = fgetc(fr);
while (catch != EOF) {
ch[index] = catch;
if (ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your result: %s\n", ch);
index = 0;
memset(ch, 0, 100);
i++;
}
else
{
index++;
}
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
I have coded a formula to read the txt file, store it in array(1D) and then reading the array to calculate the moving average(2D). Program ask the user to input two values (k1 & k2) and calculate the moving average for every value from k1 to k2 (basically to find out the best value)
Following is the code
#include<stdlib.h>
#define MAX_FILE_NAME 100
#define MAXCHAR 1000
int main()
{
FILE *fp;
int count = 0,k1=0,k2=0,k=0; // Line counter (result)
int buy[k2][count],sell[k2][count];
char filename[MAX_FILE_NAME];
char c; // To store a character read from file
// Get file name from user. The file should be
// either in current folder or complete path should be provided
printf("Enter file name or full path: ");
scanf("%s", filename);
printf("Enter the minimum rolling period for calculation : \n");
scanf("%d", &k1);
printf("Enter the maximum rolling period for calculation : \n");
scanf("%d", &k2);
// Open the file
fp = fopen(filename, "r");
// Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
// Extract characters from file and store in character c
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
count = count + 1;
// Close the file
fclose(fp);
//printf("The file %s has %d lines\n", filename, count);
FILE *myFile;
myFile = fopen(filename, "r");
//read file into array
float numberArray[count];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count; i++){
fscanf(myFile, "%f,", &numberArray[i]);
}
fclose(myFile);
for (k=k1;k<=k2;k++)
{
float n;
float data[count],mag[k2][count];
double avg,sum;
for (i=0;i<k-1;i++)
{
mag[k][i-1]=0;
sum=sum+numberArray[i];
}
for(i=k-1;i<=count;i++)
{
mag[k][i-1]=avg;
sum=sum+numberArray[i]-numberArray[i-k];
avg = sum/k;
}
// for(i=0;i<=count;i++)
// {
// printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
// if (i%3==0)
// printf("\n");
// }
}
for(k=k1;k<=k2;k++)
{
for(i=0;i<=count;i++)
printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
}
}
}
Now when I am trying to print mag[k][i] values outside the for loop, it is showing error 'mag' undeclared. But when I am putting the print command inside the loop (comment out portion in the code), it works fine.
UPDATED CODE AFTER FOLLOWING COMMENTS (STILL NOT WORKING THOUGH)
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_FILE_NAME 100
#define MAXCHAR 1000
int main()
{
FILE *fp;
int count,k1,k2,k; // Line counter (result)
char filename[MAX_FILE_NAME];
char c; // To store a character read from file
// Get file name from user. The file should be
// either in current folder or complete path should be provided
printf("Enter file name or full path: ");
scanf("%s", filename);
printf("Enter the minimum rolling period for calculation : \n");
scanf("%d", &k1);
printf("Enter the maximum rolling period for calculation : \n");
scanf("%d", &k2);
// Open the file
fp = fopen(filename, "r");
// Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
// Extract characters from file and store in character c
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
count = count + 1;
// Close the file
fclose(fp);
//printf("The file %s has %d lines\n", filename, count);
/****************
File opening and reading section
*****************************************************/
FILE *myFile;
myFile = fopen(filename, "r");
//read file into array
float numberArray[count];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count; i++){
fscanf(myFile, "%f,", &numberArray[i] );
}
fclose(myFile);
/***********************************************
Calculation of Moving Average and storing it in array
******************************************/
int buy[k2][count],sell[k2][count];
float mag[k2][count];
for (k=k1;k<=k2;k++)
{
float data[count];
double avg,sum;
for (i=1;i<k;i++)
{
mag[k][i-1]=0;
sum=sum+numberArray[i];
}
for (i=k-1;i<=count;i++)
{
mag[k][i-1]=avg;
sum=sum+numberArray[i]-numberArray[i-k];
avg = sum/k;
}
// for(i=0;i<=count;i++)
// {
// printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
// if (i%3==0)
// printf("\n");
// }
}
for (k=k1;k<=k2;k++)
{
for (i=0;i<=count;i++)
{
printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
}
}
}
The problem boils down to this: the scope of mag is limited to the inside of the for loop:
for (k = k1; k <= k2; k++)
{
...
int mag[k2][count];
...
}
// mag is out of scope here
// therefore following line won't compile:
printf("%d", mag[0][0]);
You need to declare mag outside the for loop for example like this:
int mag[k2][count];
for (k = k1; k <= k2; k++)
{
...
}
printf("%d", mag[0][0]);
...
Beware: there are other problems within your code, mentioned in the comments.
In the code below I'm trying to insert, display and delete data from a file.txt. I'm being able to insert successfully but my display function do not display correct and I don't know how to set up the logic to make the delete function. I would appreciate some help in changing the code so it can works. How can I set up the logic for it?
#include <stdio.h>
void menu() {
printf("Option 1 - Create a file and insert data:\n");
printf("Option 2 - Read file and display:\n");
printf("Option 3 - Delete content:\n");
printf("Option 4 - Exit:\n");
};
struct Book {
char title[256];
char author[256];
int pages;
int price;
};
void get() {
struct Book *book;
book = (struct Book*)malloc(sizeof(struct Book));
FILE *fPtr;
fPtr = fopen("file.txt", "w");
if (fPtr == NULL) {
printf("Fail creating file");
getch();
exit(1);
};
for (int i = 0; i < 1; i++) {
printf("Enter the book title:\n");
scanf("%s", &book[i].title);
fprintf(fPtr, "Title = %s", book[i].title);
printf("Enter the author of the book:\n");
scanf("%s", &book[i].author);
fprintf(fPtr, "Author = %s", book[i].author);
printf("Enter the number of pages:\n");
scanf("%d", &book[i].pages);
fprintf(fPtr, "Pages = %d", book[i].pages);
printf("Enter the price:\n");
scanf("%d", &book[i].price);
fprintf(fPtr, "Price = %d", book[i].price);
};
/*for (int i = 0; i < 1; i++) {
printf("%s\n", book[i].title);
printf("%s\n", book[i].author);
printf("%d\n", book[i].pages);
printf("%d\n", book[i].price);
};*/
fclose(fPtr);
};
void display() {
FILE *fPtr;
fPtr = fopen("file.txt", "r");
printf("The content of file are:\n", fPtr);
/*struct Book *book;
book = (struct Book*)malloc(sizeof(struct Book));
printf("%s %s %d %d", book.title, book.author, book.pages, book.price);*/
free(book);
fclose(fPtr);
}
int main()
{
int opt = 0;
int opt2 = 0;
int var = 0;
int validation = 0;
while (opt != 4) {
menu();
do
{
printf("Choose an option:\n");
validation = scanf_s("%d", &opt);
while (getchar() != '\n');
} while (validation != 1);
switch (opt) {
case 1:
get();
printf("Option 5 - Display data:\n");
printf("Option 6 - Delete:\n");
scanf("%d", &var);
if (var == 5) {
//FILE *fp1;
/*fp1 = fopen("file.txt", "r");*/
display();
}
else if (var == 6) {
printf("delete!");
}
break;
case 2:
printf("First insert data:\n");
break;
case 3:
printf("First insert data:\n");
break;
case 4:
return 0;
}
}
}
note : display() proposal 2
void display() {
FILE *fp;
fp = fopen("file.txt", "r");
struct Book book;
printf("%s %s %d %d", book.title, book.author, book.pages, book.price);
free(book);
fclose(fp);
}
I encourage you to rename Books to Book because that struct manages one book, not several.
About the command codes to enter, rather than 1 .. 4 what about 'c' for create, 'r' for read, 'd' for delete and 'e' for exit ?
Concerning get() :
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0, do you really manages only 1 book ?
in your fprintf move the '\n' from the beginning to the end, else your file starts by an empty line and the last line is not ended
Is it necessary to prefix each data by its kind like Title = ? To read the file content is more complex with these prefixes
Concerning display() :
you do not read the content of the file, so difficult do display it :)
you allocate a Books, do not initialize it, but write its( uninitialized) fields
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
Concerning display() :
you do not read the content of the file, so difficult do display it :)
you allocate a Books, do not initialize it, but write its( uninitialized) fields
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
Concerning deleteStudentRecord() :
getNoOfRecords() is not defined, but currently it must return 1 because you manage only one book in the file
var is not defined, nor ptr
open file2 with "w", it is a new file
fread(&var, sizeof(struct student), 1, ptr) is wrong because it supposes a line has always sizeof(struct student) but this is not the case refering to get()
fcloseall() ??? just do fclose(ptr); and fclose(ptr2), rename them fpIn and fpOut or something like will make your code more readable
"get(); proposal 2"
void get() {
FILE *fPtr;
fPtr = fopen("file.txt", "w");
struct Book book;
if (fPtr == NULL) {
printf("Fail creating file");
getch();
exit(1);
};
printf("Enter the book title:\n");
scanf("%s", &book.title);
fprintf(fPtr, "%s", book.title);
printf("Enter the author of the book:\n");
scanf("%s", &book.author);
fprintf(fPtr, "%s", book.author);
printf("Enter the number of pages:\n");
scanf("%d", &book.pages);
fprintf(fPtr, "%d", book.pages);
printf("Enter the price:\n");
scanf("%d", &book.price);
fprintf(fPtr, "%d", book.price);
/*for (int i = 0; i < 1; i++) {
printf("%s\n", book[i].title);
printf("%s\n", book[i].author);
printf("%d\n", book[i].pages);
printf("%d\n", book[i].price);
};*/
fclose(fPtr);
};
I'm having a bit of problem. I've set the string 'Absent' to all student in a file. However, I want to replace 'Absent' with 'present' when the correct ID assigned to a student is entered. In other words, 'Absent' will only change to 'Present' for a specific person at a time. I'm not sure how to implement this and I'm asking kindly if someone would help. Thanks in advance.
UPDATE::====
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <errno.h>
typedef struct record {
char *fname;
char *lname;
int code;
char *stat;
} information;
int main (void) {
int i;
char ffname[28], flname[28], ans, status[15];
int fID, j, id_, x;
FILE *kfile, *ufile;
x = 0;
j = 0;
i = 0;
char buf[150];
time_t curtime;
struct tm* loc_time;
information array[100];
printf(" **********Attendance Recording System**********\n");
printf(" MENU \n");
//Getting current time of system
curtime = time (NULL);
// Converting current time to local time
loc_time = localtime (&curtime);
strftime (buf,150, "%I:%M %p.\n", loc_time);
//prints error message if file cannot be found within the system
if ((kfile = fopen("information.txt", "r")) == NULL) //If the file path is incorrect, an error message is displayed
{
fprintf(stderr, "Error while opening file (%d: %s)\n",errno, strerror(errno)); //Error message that will be displayed if file path is incorrect
return;
}
//while the file is opened and not at the end, the strings are stored into variables which forms an array of strings
for (x = 0; x < 200; x++) {
if (fscanf(kfile, "%s %s %d", ffname, flname, &fID) != 3) //Reads the contents of the file
break;
array[x].fname = strdup(ffname);
array[x].lname = strdup(flname);
array[x].code = fID;
}
fclose(kfile);
ufile= fopen("update.txt","w");
strcpy(status, "Absent");
fprintf(ufile,"First Name Last Name ID Status Time Arrived\n");
for (i = 0; i < x; i++) {
fprintf(ufile,"%-15s%-14s%2d%12s ",(array[i].fname), (array[i].lname), (array[i].code), status);
fprintf(ufile,"%16s",(buf));
}
fclose(ufile);
while(j < x){
printf("Enter you ID: ");
scanf("%d", &id_);
strcpy(status, "Absent");
bool isPresentInFile = false;
for(i=0; i<x; i++)
{
if(array[x].code == id_)
{
printf(" %s %s?", array[x].fname, array[x].lname);
isPresentInFile = true;
break;
}
}
if(isPresentInFile)
{
strcpy(status, "present");
}
j++;
}
fprintf(ufile,"First Name Last Name ID Status Time Arrived\n");
for (i = 0; i < x; i++) {
fprintf(ufile,"%-15s%-14s%2d%12s ",(array[i].fname), (array[i].lname), (array[i].code), status);
fprintf(ufile,"%16s",(buf));
}
fclose(ufile);
getch();
return 0;
}
UPDATE #3
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <errno.h>
typedef struct record {
char *fname;
char *lname;
int code;
} information;
int main (void) {
int i;
char ffname[28], flname[28], ans, ans1, status[15];
int fID, j, id_, x;
FILE *kfile, *ufile;
x = 0;
j = 0;
i = 0;
char buf[150];
time_t curtime;
struct tm* loc_time;
information array[100];
printf(" **********Attendance Recording System**********\n");
printf(" MENU \n");
//Getting current time of system
curtime = time (NULL);
// Converting current time to local time
loc_time = localtime (&curtime);
strftime (buf,150, "%I:%M %p.\n", loc_time);
//prints error message if file cannot be found within the system
if ((kfile = fopen("information.txt", "r")) == NULL) //If the file path is incorrect, an error message is displayed
{
fprintf(stderr, "Error while opening file (%d: %s)\n",errno, strerror(errno)); //Error message that will be displayed if file path is incorrect
return;
}
//while the file is opened and not at the end, the strings are stored into variables which forms an array of strings
for (x = 0; x < 200; x++) {
if (fscanf(kfile, "%s %s %d", ffname, flname, &fID) != 3) //Reads the contents of the file
break;
array[x].fname = strdup(ffname);
array[x].lname = strdup(flname);
array[x].code = fID;
}
fclose(kfile);
while(j < x){
Next:
printf("Enter you ID: ");
scanf("%d", &id_);
strcpy(status, "Absent");
bool isPresentInFile = false;
for(i=0; i<x; i++)
{
if(array[i].code == id_)
{
printf("Are you %s %s?", array[i].fname, array[i].lname);
printf("\n");
printf("[y/n only]: ");
scanf(" %c", &ans);
isPresentInFile = true;
break;
}//end of if statement
}//end of for loop
if(isPresentInFile)
{
strcpy(status, "present");
}//end of if statement
switch (ans){
case 'y':
ufile= fopen("update.txt","w");
fprintf(ufile,"First Name Last Name ID Status Time Arrived\n");
for (i = 0; i < x; i++) {
fprintf(ufile,"%-15s%-14s%2d%12s ",(array[i].fname), (array[i].lname), (array[i].code), status);
fprintf(ufile,"%16s",(buf));
}//end of for loop
fclose(ufile);
printf("Continue?\n");
printf("[y/n]: ");
scanf(" %c", &ans1);
if(ans1 == 'y'){
break;
}//end of if statements
else if (ans1 == 'n'){
exit(EXIT_SUCCESS);
}//end of else statement to check if ans1 is equal to 'n'
case 'n':
goto Next;
break;
default:
printf("invalid entry. Try again");
}//end of switch case statememt
j++;
}//end of while
getch();
return 0;
}
From your question, I didn't get when exactly do you want to change status from "Absent" to "present".
But you can use the same strcpy() method to overwrite your status variable.
...
strcpy(status, "Absent");
if(//condition)
{
strcpy(status, "present");
}
UPDATE 1:
After reading your comment, I understood that you will prompt the user to enter an ID. And if it matches with the ID present in the file, you need to update the status to "present" and then write to the new file.
I can think of something like this:
...
// read from file
.....
int ID;
printf("Enter you ID: ");
scanf("%d", &ID);
strcpy(status, "Absent");
bool isPresentInFile = false;
for(int i=0; i<x; ++i)
{
if(array[x].code == ID)
{
isPresentInFile = true;
break;
}
}
if(isPresentInFile)
{
strcpy(status, "present");
}
...
// write to file
.....
UPDATE 2:
After reading the updated question, I notice that you are writing to the file at the end! But overwriting the status variable each time. This way you end up writing either "Absent" or "Present" for all the entries in the file (Note that it pertains to the last candidate who enters his ID!)
To avoid this, do either of the following:
Write to the file as soon as you know the status of a candidate.
while(j < x)
{
printf("Enter you ID: ");
scanf("%d", &id_);
strcpy(status, "Absent");
bool isPresentInFile = false;
for(i=0; i<x; i++)
{
if(array[x].code == id_)
{
printf(" %s %s?", array[x].fname, array[x].lname);
isPresentInFile = true;
break;
}
}
if(isPresentInFile)
{
strcpy(status, "present");
}
// write to file here
j++;
}
Also have a field called status in the structure information.
By default, keep it "Absent" for all the candidates.
Then make it "Present" only for those who enter their IDs. Finally, write it to the file.