C - How to display and delete data from a file.txt - c

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);
};

Related

C Reading records from text file in C using structure

I am trying to extract records from a text file named lib.txt. My program is a very simple library based management program where I will have to print all books by a given publisher or department.
My code is:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
struct Books
{
char name[100];
char author[100];
char publisher[100];
double price;
char branch[100];
};
typedef struct Books Books;
void main()
{
int a = 0,b=0,ch,i;
char *pb = (char *)malloc(100*sizeof(char));
Books *bk;
FILE *fp;
fp = fopen("lib.txt","r");
if(fp == NULL)
{
fprintf(stderr,"\n Error to open the file \n");
exit(1);
}
while(1)
{
if(feof(fp))
{
break;
}
char c;
c = fgetc(fp);
if(c=='\n')
{
a++;
}
}
a++;
bk = (Books *)malloc(a*sizeof(Books));
while(fread(&bk[b],sizeof(Books),1,fp)) //Even tried individual character extraction but it is not working
{
b++;
if(b==a)
{
break;
}
}
for(i=0;i<a;i++)
{
printf("%s",bk[i].name);
}
printf("1. Display books supplied by a particular publisher \n");
printf("2. Display books in a particular branch \n");
printf("3. Exit");
printf("\n");
printf("Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
printf("Enter the name of publisher \n");
scanf(" %s",pb);
printf("\nName\tAuthor\tPublisher\tPrice\tBranch\n");
for(i=0;i<a;i++)
{
if(strcmp(bk[i].publisher,pb)==0)
{
printf("%s\t%s\t%s\t%.2lf\t%s \n",bk[i].name,bk[i].author,bk[i].publisher,bk[i].price,bk[i].branch);
}
}
fflush(pb);
break;
}
case 2:
{
printf("Enter the name of branch \n");
scanf(" %s",pb);
printf("\nName\tAuthor\tPublisher\tPrice\tBranch\n");
for(i=0;i<a;i++)
{
if(strcmp(bk[i].publisher,pb)==0)
{
printf("%s\t%s\t%s\t%.2lf\t%s \n",bk[i].name,bk[i].author,bk[i].publisher,bk[i].price,bk[i].branch);
}
}
fflush(pb);
break;
}
case 3:
{
return;
}
default:
{
printf("Invalid choice");
}
}
free(bk);
free(pb);
fclose(fp);
getch();
}
The file lib.txt contains the following lines in same order as shown below:
Abc1 A1 P1 23.0 B1
Abc2 A2 P2 23.0 B2
Abc3 A3 P3 23.0 B3
Abc4 A4 P2 23.0 B4
Abc5 A5 P2 23.0 B5
Abc6 A6 P6 23.0 B6
Abc7 A7 P2 23.0 B7
Oh and they are seperated by tabs. Even tried with spaces but no change. The program is compiling fine but not generating desired output. Can anyone please please help?
Edit: Even tried individual character extraction and then splitting into substrings but failed. Please help
Here is how I would do it:
First, define some functions to help you read input (you can use them in other programs as well):
int readint(int *i)
{
char buffer[255];
if (!fgets(buffer, 255, stdin)) {
fprintf(stderr, "stdin error\n");
return 0; // failed
}
buffer[strcspn(buffer, "\n")] = '\0';
if (sscanf(buffer, "%d", i) != 1)
return 0; // failed
return 1; // success
}
char *readstr(char *str, int size)
{
if (!fgets(str, size, stdin)) {
fprintf(stderr, "stdin error\n");
return NULL;
}
str[strcspn(str, "\n")] = '\0';
return str;
}
Then your main():
int main()
{
// 1. Attempt to open file
// ------------------------------------------------------------------------
FILE *fp = fopen("lib.txt", "r");
if(!fp) {
fprintf(stderr, "Error to open the file\n");
return 1;
}
// 2. Read file text
// ------------------------------------------------------------------------
int lines_count = 7; // Depends on how many lines you have
Books *bk = malloc(lines_count * sizeof(*bk));
if (!bk) {
fclose(fp);
return 0;
}
char line[255];
int i = 0;
while(fgets(line, sizeof line, fp)) {
line[strcspn(line, "\n")] = '\0'; // Remove \n read by fgets()
char name[100];
char author[100];
char publisher[100];
double price;
char branch[100];
int ret = sscanf(line, "%99[^\t]\t%99[^\t]\t%99[^\t]\t%lf\t%99[^\t]", name, author, publisher, &price, branch);
if (ret != 5) {
printf("Line %d is problematic.\n", i+1);
}
strcpy(bk[i].name, name);
strcpy(bk[i].author, author);
strcpy(bk[i].publisher, publisher);
bk[i].price = price;
strcpy(bk[i].branch, branch);
i++;
}
fclose(fp);
// 3. User input
// ------------------------------------------------------------------------
printf("1. Display books supplied by a particular publisher\n");
printf("2. Display books in a particular branch\n");
printf("3. Exit");
printf("\n");
printf("Enter your choice: ");
int ch;
readint(&ch); // Ignored error checking for the sake of simplicity
char pb[100];
switch(ch)
{
case 1:
printf("Enter the name of publisher: ");
readstr(pb, sizeof(pb));
printf("\nName\tAuthor\tPublisher\tPrice\tBranch\n");
for(i = 0; i < lines_count; i++)
if(!strcmp(bk[i].publisher, pb))
printf("%s\t%s\t%s\t%.2lf\t%s \n", bk[i].name, bk[i].author, bk[i].publisher, bk[i].price, bk[i].branch);
break;
case 2:
printf("Enter the name of branch: ");
readstr(pb, sizeof(pb));
printf("\nName\tAuthor\tPublisher\tPrice\tBranch\n");
for(i = 0; i < lines_count; i++)
if(!strcmp(bk[i].branch, pb))
printf("%s\t%s\t%s\t%.2lf\t%s \n",bk[i].name, bk[i].author, bk[i].publisher ,bk[i].price, bk[i].branch);
break;
case 3:
return 0;
default:
printf("Invalid choice\n");
}
free(bk);
}
Make sure lib.txt contains tabs, not spaces. You should verify if your editor is replacing tabs with spaces.
Few things to consider:
main() should always return int, not void.
Use fgets() to read input from the user, and sscanf() to parse it. You should avoid using scanf() as much as you can.

Adding an array of structs into a file in c

I have a code where I am able to add my struct array to a file, but am unable to continue adding contacts to my struct array like I should.
Here are my variables:
struct contact { // Data structure that holds contact information
char FirstName[10]; // Array for first name
char LastName[10]; // Array for last name
int PhoneNum; // Phone number
};
int Choice = 0;
int n = 0;
int size = 1;
struct contact *con = (struct contact *)malloc(size * sizeof(struct contact));
int a = 0;
int b = 0;
int SortChoice = 0;
int iRandNum = 0;
int Valid = 0;
char temp[10];
int tempNum = 0;
char File[20];
int status = 0;
FILE *pRead;
FILE *pWrite;
Here is the add contact part:
if (n == size)
{
size = size * 2;
con = (struct contact*)realloc(con, size * sizeof(struct contact));
}
// Records the information given into the structure
printf("\nYou chose to add a contact.");
printf("\nFirst name: ");
scanf("%s", con[n].FirstName);
printf("\nLast name: ");
scanf("%s", con[n].LastName);
printf("\nPhone number (Numbers only): ");
scanf("%d", &con[n].PhoneNum);
printf("\nRecord added to the phone book.");
// Prints out the given information
printf("\n\nNew contact:");
printf("\nFirst name: %s", con[n].FirstName);
printf("\nLast name: %s", con[n].LastName);
printf("\nPhone number: %d", con[n].PhoneNum);
printf("\nContact number is %d", n);
printf("\n");
n += 1;
And here is the file part:
printf("\nYou chose to store all contacts to a file.");
if (status == 0){
printf("\nWhat would you like to name your file?\n");
scanf("%s", &File);
printf("\nFile name is %s", File);
pWrite = fopen(File, "w");
if (pWrite == 0){
printf("\nFile not opened");
}
else {
for (a = 0; a < n; a++){
fwrite(&con[a], sizeof(struct contact), 1, pWrite);
}
fclose(pWrite);
pRead =fopen(File, "r");
printf("\n\nContacts added to %s", File);
printf("\n\nContacts in file:\n");
while (fread(&con[a], sizeof(struct contact),1, pRead)){
printf("\n");
printf("\nFirst name: %s", con[a].FirstName);
printf("\nLast name: %s", con[a].LastName);
printf("\nPhone number: %d", con[a].PhoneNum);
printf("\n");
}
fclose(pRead);
}
}
If you guys can figure out where I've gone wrong, and potentially why I can't continue to access the file I created that would be great. Thanks

i am getting some unreported values in my program

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;
}

C doesn't load info from file (fread, fwrite)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLENG 50 //just a random value
typedef struct Song
{
char *name;
char *nameSong;
char *timeSong;
int date;
} Song;
void saveToFile(Song *x, int *songCount) //Saves info to the binary file
{
FILE *f = fopen("array.txt", "w");
if (f == NULL)
{
printf("Error\n");
}
fwrite(songCount, sizeof(int), 1, f);
fwrite(x, sizeof(struct Song), (*songCount), f);
fclose(f);
}
void readSong(Song *x, int *songCount) //Reads info fromt he file and writes it
{
FILE *fr = fopen("array.txt", "r");
if (fr == NULL)
{
printf("Error\n");
}
printf("Songs:\n");
fread(songCount, sizeof(int), 1, fr);
fread(x, sizeof(struct Song), (*songCount), fr);
for(int i=0; i < (*songCount); i++)
{
printf("%d. %s %s %s %d\n", (i+1), x[i].name, x[i].nameSong, x[i].timeSong, x[i].date);
}
fclose(fr);
}
void insertSong(Song *x, int Count) //Inserts new song into the array.
{
printf("\nInsert name of the band:\n");
x[Count].name=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].name);
printf("Insert name of the song:\n");
x[Count].nameSong=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].nameSong);
printf("Insert length of the song:\n");
x[Count].timeSong=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].timeSong);
printf("Insert then song was created:\n");
scanf("%d", &(x[Count].date));
printf("\n");
}
main()
{
int songCount, menuOption;
Song *x=malloc(SLENG*sizeof(char)+SLENG*sizeof(char)+SLENG*sizeof(char)+sizeof(int));
printf("1. insert song\n 2. load from file\n ");
scanf("%d", &menuOption);
switch(menuOption)
{
case(1) :
printf("Insert how many songs do you want to input?\n");
scanf("%d", &songCount);
for(int i=0; i<songCount; i++)
{
insertSong(x, i);
}
saveToFile(x, &songCount);
break;
case(2) :
readSong(x, &songCount);
break;
}
}
I have an assingment to write a programm which would input some data into file and could read that data from that file, the problem is probably with fwrite or fread, couse it seems to crash everytime I try to load the and write the data from file. Any ideas why is it not working properly? And can I even do it like this as it is dynamic struct array. Thanks in advance.
In order to save the structure to a file, it must only contain scalar values, not pointers into memory objects. Modify your structure to use arrays instead of pointers:
typedef struct Song {
char name[SLENG];
char nameSong[SLENG];
char timeSong[SLENG];
int date;
} Song;
And modify the code accordingly, but note that:
saving and reading the structures to and from a file requires opening it in binary mode "wb" and "rb".
it is very misleading to name a binary file array.txt.
you do not need to pass the address of the count when writing to the file, but you need to pass the address of the array pointer when reading as you do not know yet how much memory to allocate.
Here is the modified code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLENG 50 // this value is used in the file format
typedef struct Song {
char name[SLENG];
char nameSong[SLENG];
char timeSong[SLENG];
int date;
} Song;
int saveToFile(Song *x, int songCount) { //Saves info to the binary file
FILE *f = fopen("array.bin", "wb");
if (f == NULL) {
printf("Error\n");
return -1;
}
fwrite(songCount, sizeof(int), 1, f);
int written = fwrite(x, sizeof(struct Song), songCount, f);
fclose(f);
return written;
}
int readSong(Song **x, int *songCount) { //Reads info from the file and writes it
int count = 0;
FILE *fr = fopen("array.bin", "rb");
if (fr == NULL) {
printf("Error\n");
return -1;
}
printf("Songs:\n");
fread(&count, sizeof(int), 1, fr);
*x = calloc(count, sizeof(Song));
if (*x == NULL) {
printf("Cannot allocate %d bytes of memory\n", count);
fclose(fr);
return -1;
}
int found = fread(*x, sizeof(struct Song), count, fr);
for (int i = 0; i < found; i++) {
printf("%d. %s %s %s %d\n", i + 1,
(*x)[i].name, (*x)[i].nameSong, (*x)[i].timeSong, (*x)[i].date);
}
fclose(fr);
return *songCount = found;
}
void insertSong(Song *x, int Count) { //Inserts new song into the array.
printf("\nInsert name of the band:\n");
scanf("%49s", x[Count].name);
printf("Insert name of the song:\n");
scanf("%49s", x[Count].nameSong);
printf("Insert length of the song:\n");
scanf("%49s", x[Count].timeSong);
printf("Insert then song was created:\n");
scanf("%d", &(x[Count].date));
printf("\n");
}
int main(void) {
int songCount, menuOption;
Song *x = NULL;
printf("1. insert song\n 2. load from file\n ");
scanf("%d", &menuOption);
switch (menuOption) {
case 1:
printf("Insert how many songs do you want to input?\n");
if (scanf("%d", &songCount) == 1) {
x = calloc(songCount, sizeof(Song));
for (int i = 0; i < songCount; i++) {
insertSong(x, i);
}
saveToFile(x, songCount);
}
break;
case 2:
readSong(&x, &songCount);
break;
}
free(x);
x = NULL;
return 0;
}

Console app menu not working in C

guys! So I have an assignment to create a structure that includes variables based on what information I need to store and to bring out a menu that calls different functions and does different things. The problems is that for some reason my createFile function is not working at all and I've been looking for errors for 2 days and I simply cannot spot where this is coming from.
Ignore the changeStud funcion as I'm still working on it. I simply want to create my file when I enter the name for it and then chose the nnumber of the function. (in my case > enter filename> enter 1> it just loops the menu function and it should create a file)
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char ime[50];
char fn[10];
int ocfiz, ocmat, ocpro;
};
char filename[20];
FILE *fd;
Student ps;
void createFile() {
fd = fopen(filename, "wb");
fclose(fd);
printf("File created!\n");
}
void readStud(Student *s) {
printf("Enter data for new student");
getchar();
printf("Enter student name:");
gets_s(s->ime);
printf("\nEnter FN:");
scanf_s("%s", s->fn);
printf("\nEnter marks for Maths, Programming, Physics");
scanf_s("%d %d %d", &s->ocmat, &s->ocpro, &s->ocfiz);
getchar();
}
void addStud() {
fd = fopen(filename, "a+b");
char c;
do {
readStud(&ps);
fwrite(&ps, sizeof(ps), 1, fd);
printf("More Students? (y/n) : ");
c = getchar(); getchar();
} while (c == 'y');
fclose(fd);
}
void writeAllStud() {
fd = fopen(filename, "rb");
printf("students in file\n");
fread(&ps, sizeof(ps), 1, fd);
while (!feof(fd)) {
printf("%s fn: %s ocmat: %d ocpro: %d ocfiz: %d", ps.ime, ps.fn, ps.ocmat, ps.ocpro, ps.ocfiz);
fread(&ps, sizeof(ps), 1, fd);
}
fclose(fd);
}/*
void changeStud() {
char fn2[50];
printf("enter FN:");
gets_s(fn2);
fd = fopen(filename, "r+b");
fread(&ps, sizeof(ps), 1, fd);
while (!feof(fd)) {
if (strcmp(ps.fn, fn2)==0) {
fseek(fd, -(long) sizeof(ps), SEEK_CUR);
fwrite(&ps, sizeof(ps, 1, fd));
break;
}
}
}*/
void Avg() {
}
void exportData() {
FILE *txt;
txt = fopen("students.txt", "wt");
fd = fopen(filename, "rb");
fread(&ps, sizeof(ps), 1, fd);
while (!feof(fd)) {
fprintf(txt, "%s %s marks fiz%d mat%d prog%d\n", ps.fn, ps.ime, ps.ocfiz, ps.ocmat, ps.ocpro);
fread(&ps, sizeof(ps), 1, fd);
}
fclose(fd);
fclose(txt);
printf("students have been written to a text file.\n");
}
void main() {
printf("Enter file name:");
gets_s(filename);
int c;
do {
printf("\nMenu:\n");
printf("0 Exit\n");
printf("1 Create file\n");
printf("2 Add new student data\n");
printf("3 Change data from FN\n");
printf("4 AVG marks for maths, programming, physics\n");
printf("5 export all AVG marks to .txt file\n");
scanf("%d", &c);
switch (c) {
case 1: createFile; break;
case 2: addStud; break;
//case 3: changeStud; break;
case 4: Avg; break;
case 5: exportData; break;
}
} while (c != 0);
}
i think you should use your struct variable like this:
struct Student {
char ime[50];
char fn[10];
int ocfiz, ocmat, ocpro;
}ps;
or use
struct Student ps;
instead of just student ps,or you can decleare it in main function..And passing a struct in a functin is
void readStud( struct Student *s)() {
//your code...
}

Resources