I'm writing a program that allows users to add a question that has 4 answers, right answer, date, author and level of complexity, also the program has functions for reading all the questions and deleting a question. When I choose the option add a question and i insert all of the characteristics the message box for the error appears it also doesn't allow me to delete or see the `.
questions. i need help.
Why is the following code not allowing me to delete a question?
void edit()
{
char filename[2];
int y;
int q,ft,s,t, fr,d,a,l,tr,n,da;
FILE *f, *f1;
f=fopen("pff.txt","r");
if (f==NULL)
{
perror ("Error!");
}
fscanf(f,"%d",&y);
printf(" " );
gets(question.name);
n=sizeof(question.name);
printf("Name : ");
gets(question.name);
q=sizeof(question.name);
printf("Answer 1: ");
gets(question.first);
ft=sizeof(question.first);
printf("Answer 2: ");
gets(question.second);
s=sizeof(question.second);
printf("Answer 3: ");
gets(question.third);
t=sizeof(question.third);
printf("Answer 4: ");
gets(question.fourth);
fr=sizeof(question.fourth);
printf("Right answer (1-4): ");
scanf("%d",&question.tr);
printf(" ");
gets(question.date);
da=sizeof(question.date);
printf("Date: ");
gets(question.date);
d=sizeof(question.date);
printf(" Author: ");
gets(question.author);
t=sizeof(question.author);
printf("Level (0-2): ");
scanf("%d",&question.level);
fclose (f);
sprintf(filename, "%d.bin", y+1);
puts (filename); f=fopen(filename,"wb");
fwrite(&q,sizeof(int),1,f);
fwrite(question.name,sizeof(question.name),1,f);
fwrite(&ft,sizeof(int),1,f);
fwrite(question.first,sizeof(question.first),1,f);
fwrite(&s,sizeof(int),1,f);
fwrite(question.second,sizeof(question.second),1,f);
fwrite(&t,sizeof(int),1,f);
fwrite(question.third,sizeof(question.third),1,f);
fwrite(&fr,sizeof(int),1,f);
fwrite(question.fourth,sizeof(question.fourth),1,f);
fwrite (&question.tr, sizeof (int),1,f);
fwrite(&d,sizeof(int),1,f);
fwrite(question.date, sizeof(question.date),1,f);
fwrite(&a,sizeof(int),1,f);
fwrite(question.author,sizeof(question.author),1,f);
fwrite(question.level,sizeof(int),1,f);
fclose(f);
f=fopen("pff.txt","w");
fprintf(f,"%d",y+1);
fclose(f);
}
The buffer filename is too short to store the name of file. It should be at least 16-character long if int is 32-bit long.
Not knowing the actual definition, the line fwrite(question.level,sizeof(int),1,f); seems wrong because the address of question.level is passed to scanf with use of %d specifier, and I guess its type is int. You should include proper header and enable compiler warnings.
You shouldn't pass NULL, which may be returned from fopen, to fscanf.
You shouldn't use gets from the standard library, which has an unavoidable risk of buffer overrun, and is deprecated in C99 and removed in C11.
Try this (the problem that gets is used isn't resolved here):
void edit()
{
char filename[32]; /* allocate enough buffer */
int y;
int q,ft,s,t, fr,d,a,l,tr,n,da;
FILE *f, *f1;
f=fopen("pff.txt","r");
if (f==NULL)
{
perror ("Error!");
return; /* avoid using NULL as file pointer */
}
fscanf(f,"%d",&y);
printf(" " );
gets(question.name);
n=sizeof(question.name);
printf("Name : ");
gets(question.name);
q=sizeof(question.name);
printf("Answer 1: ");
gets(question.first);
ft=sizeof(question.first);
printf("Answer 2: ");
gets(question.second);
s=sizeof(question.second);
printf("Answer 3: ");
gets(question.third);
t=sizeof(question.third);
printf("Answer 4: ");
gets(question.fourth);
fr=sizeof(question.fourth);
printf("Right answer (1-4): ");
scanf("%d",&question.tr); /* warning: don't place newline character after the number to be read here, or what is read to question.date may become not what is wanted */
printf(" ");
gets(question.date);
da=sizeof(question.date);
printf("Date: ");
gets(question.date);
d=sizeof(question.date);
printf(" Author: ");
gets(question.author);
t=sizeof(question.author);
printf("Level (0-2): ");
scanf("%d",&question.level);
fclose (f);
sprintf(filename, "%d.bin", y+1);
puts (filename);
f=fopen(filename,"wb");
if (f == NULL) return; /* add error check */
fwrite(&q,sizeof(int),1,f);
fwrite(question.name,sizeof(question.name),1,f);
fwrite(&ft,sizeof(int),1,f);
fwrite(question.first,sizeof(question.first),1,f);
fwrite(&s,sizeof(int),1,f);
fwrite(question.second,sizeof(question.second),1,f);
fwrite(&t,sizeof(int),1,f);
fwrite(question.third,sizeof(question.third),1,f);
fwrite(&fr,sizeof(int),1,f);
fwrite(question.fourth,sizeof(question.fourth),1,f);
fwrite (&question.tr, sizeof (int),1,f);
fwrite(&d,sizeof(int),1,f);
fwrite(question.date, sizeof(question.date),1,f);
fwrite(&a,sizeof(int),1,f);
fwrite(question.author,sizeof(question.author),1,f);
fwrite(&question.level,sizeof(int),1,f); /* add & before question.level */
fclose(f);
f=fopen("pff.txt","w");
if (f != NULL) { /* add error check */
fprintf(f,"%d",y+1);
fclose(f);
}
}
Related
Recently I am working on a beginner projects. But I was stuck for days without knowing how to update a file. Then I found I can do it with binary files, so I started using binary files instead of normal files. But now when I write into binary files it works (I assume), but when I read from it, it gives me segmentation fault (core dumped).
Here is my structs
struct date{ // structure for dates
int mm, dd, yyyy;
};
struct {
char *initials, *name, *email, *acc_type; // unchangeable values
char id_num[11], occupation[25], address[100]; // changeable values
int phone, acc_num, balance;
struct date birth_day; // structure for birth day
} new_acc;
Here is my writing function...
void create_new(void)
{
// Allocating memory for each member in struct
new_acc.name = (char *) malloc(sizeof(new_acc.name));
new_acc.initials = (char *) malloc(sizeof(new_acc.initials));
new_acc.email = (char *) malloc(sizeof(new_acc.email));
new_acc.acc_type = (char *) malloc(sizeof(new_acc.acc_type));
system("clear");
puts("Answer the questions to make a account");
time_t l; // To generate a number
srand((unsigned) time(&l)); // Generating a random number to account number
new_acc.acc_num = l; // Assign l value to acc_num var in struct
printf("Enter your full name: ");
scanf(" %100[^\n]", new_acc.name); // scan for name, 100 characters, and also accepting spaces
printf("Enter your name with initials: ");
scanf(" %100[^\n]", new_acc.initials);
printf("Enter your birthday (mm/dd/yyyy): ");
scanf(" %d %d %d", &new_acc.birth_day.mm, &new_acc.birth_day.dd, &new_acc.birth_day.yyyy)
printf("Enter your address: ");
scanf(" %100[^\n]", new_acc.address);
printf("Enter your phone number: ");
scanf(" %10d", &new_acc.phone);
printf("Enter your id number: ");
scanf(" %10[0-9a-zA-Z]", new_acc.id_num);
printf("Enter your occupation: ");
scanf(" %50[^\n]", new_acc.occupation);
printf("Enter your email address:");
scanf(" %s", new_acc.email);
printf("Enter the account type:\n");
printf("\t#Saving\n\tFixed (1 year)\n\tFixed (2 year)\n\tFixed (3 year)\n");
scanf(" %20s", new_acc.acc_type);
printf("Enter amount to deposite: $");
scanf(" %d", &new_acc.balance);
FILE *fp;
fp = fopen("employees", "a"); // Opening file in append mode
if (fp == NULL) // If file couldn't open
puts("Cannot open a file...");
// Here, I also used while loop, but I don't know how to break it so I used for loop
for (int i = 0; i <= 12; ++i) // Looping 12 times
fwrite(&new_acc, sizeof(new_acc), 1, fp); // writting to file
fclose(fp); // Closing file
// freeing memory after use
free(new_acc.name);
free(new_acc.initials);
free(new_acc.email);
free(new_acc.acc_type);
int out;
printf("Successfully created a account!\nYour account number is %d\n", new_acc.acc_num);
printf("Press 1 to exit, and 0 to go to main menu...");
scanf("%d", &out);
switch (out){
case 1:
exit(0);
break;
case 0:
menu();
break;
}
}
And here my reading coding snippet also
FILE *fp;
fp = fopen("employees", "r");
if (fp == NULL)
puts("Cannot open a file...");
for (int i = 0; i <= 12; ++i)
fread(&new_acc, sizeof(new_acc), 1, fp);
fclose(fp);
printf("%d\n", new_acc.acc_num); // It only prints acc_num
// After that it gives me segmentation fault
printf("%s\n", new_acc.name);
printf("%s\n", new_acc.initials);
printf("%s\n", new_acc.birth_day);
printf("%s\n", new_acc.address);
printf("%d\n", new_acc.phone);
printf("%s\n", new_acc.id_num);
printf("%s\n", new_acc.occupation);
printf("%s\n", new_acc.email);
printf("%s\n", new_acc.acc_type);
printf("%d\n", new_acc.balance);
All I don't sure correct is writing and reading bin file...
I was wrong at writing into bin file and also reading from it.
First of all I need to thank to #lulle.
As he mentioned in comments I changed char* in struct into char arrays.
char initials[80], name[250], email[100], acc_type[25];
And I also change file mode. I use ab to writing snippet. And rb in reading snippet.
And I changed my writing snippet.
Here I looped over 12 times, this wrote every record 12 time. Sad ah?
This happened because I used just address of struct &new_acc in fwrite. If you use just address of a struct in fwrite`` or fread``` it will write your whole struct. That's what happened to me. I wrote the whole struct 12 time.
for (int i = 0; i <= 12; ++i) // Looping 12 times
fwrite(&new_acc, sizeof(new_acc), 1, fp); // writting to file
So instead of looping I changed it into this
fwrite(&new_acc, sizeof(new_acc), 1, fp); \\ This line will write whole struct
But if you want to use members of struct instead of a whole struct, you are free to use a loop. Here is a example. This example is same as above one. But remember to use i or any variable that you used in for loop when writing to file. Instead of i, if you used member name, It will also write 12 times (or as far as you are looping...)
for (int i = 0; i <= 12; ++i) // Looping 12 times
fwrite(&new_acc.[i], sizeof(new_acc.[i]), 1, fp); // writting to file
And the same thing happened to reading part (I guess...).
So I changed the code snippet like below
FILE *fp;
fp = fopen("employees", "rb");
if (fp == NULL)
puts("Cannot open a file...");
int i = 0;
while(fread(&new_acc, sizeof(new_acc), 1, fp) != 0){ /* use fread one time */
printf("%d\n", new_acc.acc_num);
printf("%s\n", new_acc.name);
printf("%s\n", new_acc.initials);
printf("%s\n", new_acc.birth_day);
printf("%s\n", new_acc.address);
printf("%d\n", new_acc.phone);
printf("%s\n", new_acc.id_num);
printf("%s\n", new_acc.occupation);
printf("%s\n", new_acc.email);
printf("%s\n", new_acc.acc_type);
printf("%d\n", new_acc.balance);
++i;
}
fclose(fp);
This question already has answers here:
When should I use ampersand with scanf()
(3 answers)
Closed 2 years ago.
I am having problem with a specific part of the code which I cant find any answer to yet. Here the fscanf() was not able to read the value of file until I added an '&' sign before add.age variable in this section. I got the problem solved but still cant figure out how it works. I mean why do I need to provide address of an integer data type and not of any string. Can any one explain please?
while(fscanf(fp, "%s %d %s", add.name, &add.age, add.dept)!=EOF)
{
printf("%s\t\t %d\t\t %s\n", add.name, add.age, add.dept);
}
This is the full code that I wrote for reference if you want
#include<stdio.h>
#include<stdlib.h>
void add_user(void);
void see(void);
void see_all(void);
struct student
{
char name[50];
char dept[50];
int age;
}add, check;
int main()
{
int choice;
printf("1. Add \n2. See \n3. See All \nEnter choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:add_user();
break;
case 2:see();
break;
case 3:see_all();
break;
default:printf("Wrong Input");
}
}
void add_user()
{
FILE *fp;
printf("Enter name : ");
fflush(stdin);
gets(add.name);
printf("Enter age : ");
scanf("%d", &add.age);
printf("Enter department : ");
fflush(stdin);
gets(add.dept);
fp=fopen("Creating a file with multiple records and reading it.txt", "a+");
if(fp==NULL)
{
printf("file pointer is null");
exit(0);
}
fprintf(fp, "%s %d %s\n", add.name, add.age, add.dept);
fclose(fp);
main();
}
void see()
{
}
void see_all()
{
FILE *fp;
fp=fopen("Creating a file with multiple records and reading it.txt", "r");
if(fp==NULL)
{
printf("file pointer is null");
exit(0);
}
printf("Name\t\t Age\t\t Department\n");
while(fscanf(fp, "%s %d %s", add.name, &add.age, add.dept)!=EOF)
{
printf("%s\t\t %d\t\t %s\n", add.name, add.age, add.dept);
}
fclose(fp);
}
A "string" in C (in your case a character array) already decays to a pointer indicating the address in memory of the first character. There's no such mechanism for a single int, and as a result you need to explicitly pass an address that holds an int to scanf, which is done by prefixing a variable or lvalue expression with &. scanf needs pointers so that it can write the data it scanned into memory you control and can use.
fscanf (and other scanf variants) take pointers so they can assign the read values to them. In the case of strings, you already have a char * (read: char pointer), so you don't need and additional &).
Essentially, I printed to a binary file using fseek() and fwrite(). However, I want to read the contents from a specific line into a structure. I also used fseek() and fread() to obtain the contents. I prompted the user to enter a code. From what I have learnt, I would use the value obtained from the user to use in the fseek function to get the specific line to start read from. Apparently, the fseek to read the contents does not work, I am getting gibberish essentially when it is displayed on the screen. Assistance is greatly appreciated.
#include <conio.h>
#include <stdio.h>
typedef struct registered
{
int compcode;
char compname[20];
int pinID;
int custID;
char IDtype[15];
int compID;
}REGISTERED;
void AddUpdate(REGISTERED info);
void SellPetrol();
void main(){
REGISTERED info = {0, "Apple", 0, 0, "passport", 0};
REGISTERED list;
AddUpdate(info);
SellPetrol();
}
void AddUpdate(REGISTERED info){
int choice;
FILE *registryfile = NULL;
registryfile = fopen("Sales.dat", "ab");
if (registryfile == NULL){
perror("Error: ");
}
else{
do{
printf("Company Code: ");
scanf("%d", &info.compcode);
printf("Company Name: ");
scanf("%s", &info.compname);
printf("Pin: ");
scanf("%d", &info.pinID);
printf("Customer ID: ");
scanf("%d", &info.custID);
printf("ID type: ");
scanf("%s", &info.IDtype);
printf("Company ID: ");
scanf("%d", &info.compID);
fseek(registryfile, (info.compcode - 1) * sizeof(REGISTERED), SEEK_SET);
fwrite(&info, sizeof(REGISTERED), 1, registryfile);
printf("Enter choice: ");
scanf("%d", &choice);
}while(choice == 1);
}
printf("\tCompany Code: %d\t\n", info.compcode);
printf("\tCustomer ID: %d\t\n", info.custID);
fclose(registryfile);
}
void SellPetrol(){
int code = 0, PIN;
REGISTERED list;
FILE *registryfile = NULL;
registryfile = fopen("Sales.dat", "rb");
if (registryfile == NULL){
perror("Error: ");
}
else{
printf("Please enter the company code: ");
scanf("%d", &code);
// printf("Please enter the PIN: ");
// scanf("%d", &PIN);
rewind(registryfile);
fseek(registryfile, (code - 1) * sizeof(REGISTERED), SEEK_SET);
fread(&list, sizeof(REGISTERED), 1, registryfile); //reads data into list
fflush(stdin);
printf("Company Code: %d\n", list.compcode);
printf("Company Name: %s\n", list.compname);
printf("Pin: %d\n", list.pinID);
printf("Customer ID: %d\n", list.custID);
printf("ID Type: %s\n", list.IDtype);
printf("Company ID: %d\n", list.compID);
}
fclose(registryfile);
}
It seems whichever method you're using to learn C is causing troubles, as the mistakes you seem to be making are common. I suggest reading a book, such as K&R2E... Do the exercises as you stumble across them; don't move on until you've completed them, and ask questions about them if necessary.
Don't fflush(stdin). fflush doesn't do what you think it does.
Check return values for functions such as fopen, scanf, fseek, fread, even fwrite. You'll probably find that your fread or scanf is returning a value indicating failure, hence the gibberish you speak of.
Be aware that C uses pass-by-value semantics ONLY. The source of at least one error in your code is a misunderstanding regarding these semantics. Namely, AddUpdate has no way to modify the variable declared within main, as it recieves a copy of that variable; at this point it seems void AddUpdate(REGISTERED info) should be void AddUpdate(void) and info should be declared within AddUpdate.
scanf("%s", &info.compname); probably doesn't do what you think it does. The %s directive tells scanf to read (metalinguistically speaking) a word (that is, a whitespace-delimitered token), not a line (a newline delimitered token), of user input. You probably want int x = scanf("%19[^\n]", info.compname); or better yet, char *x = fgets(info.compname, sizeof info.compname, stdin);...
void main() is unportable, and so is #include <conio.h>. You probably want int main(void) and ... you don't appear to be using any functions from <conio.h>, so you probably don't want anything in place of that. In C99, a main function that has no return statement will implicitly return 0; without a warning issued.
I'm supposed to be creating a small client managing program for a private clinic (before you ask, yes this is college work) but I seem to have found 2 bugs that don't allow me to progress on this.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct DATA {
int dia, mes, ano;
};
struct cliente {
char pnome[15];
char snome[15];
char telefone[10];
char bi[10];
float peso, altura;
struct DATA data;
};
int main () {
FILE *c, *tempo;
int op, i;
int stelemovel, sbi;
char filename[15];
struct cliente a;
printf("1 - procurar\n");
printf("2 - inserir novo\n");
printf("3 - gravar\n");
printf("4 - sair\n");
scanf("%d", &op);
switch(op) {
**(...)**
case 2 :
printf("novo cliente. Dados: \n");
tempo = fopen("temp.txt", "a"); //opens a file to store the data on so I can copy it later, this was an attempt to correct a bug I will explain ahead
printf("primeiro nome \n");
scanf("%s", &a.pnome); //scan the first name
fprintf(tempo, "%s", a.pnome); //print to tempo file
printf("segundo nome \n");
scanf("%s", &a.snome); //second name
fprintf(tempo, "%s", a.snome);// print
printf("peso\n"); //you get the picture so far
do{
scanf("%f", &a.peso);
} while (a.peso<1);
fprintf(tempo, "%.2f", a.peso);
printf("altura\n");
do{
scanf("%f", &a.altura);
} while (a.altura<1);
fprintf(tempo, "%.2f", a.altura);
printf("por favor insira data nascimento (dia mes ano)\n");
do {
printf("dia\n");
scanf("%d", &a.data.dia);
} while (a.data.dia<1 || a.data.dia>31);
fprintf(tempo, "%d", a.data.dia);
do {
printf("mes\n");
scanf("%d", &a.data.mes);
} while (a.data.mes<1 || a.data.mes>12);
fprintf(tempo, "%d", a.data.mes);
do {
printf("ano\n");
scanf("%d", &a.data.ano);
} while (a.data.ano<1);
fprintf(tempo, "%d", a.data.ano);
printf("numero telefone\n");
do {
scanf("%s", &a.telefone);
} while (strlen(a.telefone)!=9);
fprintf(tempo, "%d", a.telefone);
printf("numero BI\n");
do {
scanf("%s", &a.bi);
} while (strlen(a.bi)!=9);
fprintf(tempo, "%d", a.bi);
/* printf("%s, %s\n %.2f, %.2f\n %d, %d, %d\n %s, %s\n", a.pnome, a.snome, a.peso, a.altura, a.data.dia, a.data.mes, a.data.ano, a.telefone, a.bi); */
/*this was something I used to test out if the data was saving properly
which is EXCEPT for the a.telefone and the a.bi, they're being printed together for some reason
*/
return main();
case 3 :
printf("nome do ficheiro\n");
scanf("%s", &filename);
c = fopen(filename, "a");
printf("%s, %s\n %.2f, %.2f\n %d, %d, %d\n %s, %s\n", a.pnome, a.snome, a.peso, a.altura, a.data.dia, a.data.mes, a.data.ano, a.telefone, a.bi);
fprintf(c, "%s, %s\n %.2f, %.2f\n %d, %d, %d\n %s, %s\n", a.pnome, a.snome, a.peso, a.altura, a.data.dia, a.data.mes, a.data.ano, a.telefone, a.bi);
/*this part basically should copy all I scanned in case 2 and print it to a document but I can't seem to be able to write on the file. The file is created opened but there's never any content on it */
return main();
**(...)**
return 0;
}
This is the bug I get when printing, a.bi gets printed normally next though which basically tells me the problem is on a.telefone but I can't seem to see it.
I'm writing this here because I'm really out of ideas, slightly saturated too and as you can probably guess I'm not exactly a pro on files. Thanks in advance for any help being provided though.
I'm sure the solution is probably simple but I can't seem to see it at this point...
EDIT
Now if ya guys can help me on why I'm not able to print the stuff I scan to a file this matter can be considered closed.
EDIT 2
Ok seems like it's printing to a file but it's not separating the words through commas.
The reason your code is printing telephone and bi together is because you didn't leave enough space for the '\0' at the end of the string. Strings in C are null terminated. This also indicates your not sanitizing your inputs. Doing scanf("%s", str); is very dangerous and leads to buffer exploits. You should provide a width to it like scanf("%8s", str); or consider using something like fgets().
The telephone string:
char telefone[9];
Is too small to held the phone number you punched in plus the null tereminator of the string. Changing it to something larger as:
char telefone[16];
Will work. But the probllem here is that you don't make any check on the input data for buffer overflow.
Always check for max input.
char telefone[9];
This buffer can hold a string of up to 8 characters, plus terminating '\0' as the 9th element. You are experiencing buffer overflow by writing XXX XXX XXX to it. Enlarge the buffer to at least 10 characters and always check the returned value of scanf in each call:
char telefone[10];
if (scanf("%s", &a.telefone) != 0)
// handle error
Consider using fgets to avoid buffer overflow:
char buf[10];
fgets(buf, sizeof(buf), stdin);
a major problem with the posted code is repeatedly calling fopen() with the same variable on a file that is already open.
Suggest calling fclose() before every new recursion AND before exiting the program.
I wrote a program that collects user data and saves it to a file. At the moment when he wants to view the file, the program loops and shows only the first record. I do not know what this error is caused.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *fptr;
struct notification {
char name[50];
char lastname[50];
char price[10];
char descreption[100];
}notification;
void insertRecord()
{
fptr=fopen("G:\\file.txt","a+");
fflush(stdin);
printf("Podaj imie: ");
gets(notification.name);
printf("Podaj nazwisko: ");
gets(notification.lastname);
printf("Podej cene: ");
gets(notification.price);
printf("Podaj opis usterki: ");
gets(notification.descreption);
strcat(notification.descreption,"\n");
if(fwrite(¬ification,sizeof(notification),1,fptr) != 1)
{
perror("Blad: ");
} else{
printf("Dane dodane poprawnie\n");
}
fclose(fptr);
}
void readDatabase()
{
struct notification *object2=malloc(sizeof(struct notification));
fptr=fopen("G:\\file.txt","rb");
fread(object2,sizeof(struct notification),1,fptr);
while(!feof(fptr))
{
printf("Imie: %s\n", object2->name);
printf("Nazwisko: %s\n", object2->lastname);
printf("Cena: %s\n", object2->price);
printf("Opis: %s\n", object2->descreption);
printf("==========\n");
}
fclose(fptr);
}
int main() {
int i,option=0,check=0;
do{
printf("1) Dodaj rekord do bazy \n");
printf("2) Odczytaj rekordy z bazy \n");
printf("0) Zakoncz program \n");
scanf("%d", &option);
switch (option)
{
case 1:
insertRecord();
break;
case 2:
readDatabase();
break;
default:
break;
}
}while(check == 0); //petla dziala dopóki zmienna check bedzie równa 0
}
EDIT:
Correct insertRecord function:
void insertRecord()
{
fptr=fopen("G:\\file.txt","a+");
fflush(stdin);
struct notification *obj = malloc(sizeof(struct notification));
printf("Podaj imie: ");
gets(obj->name);
printf("Podaj nazwisko: ");
gets(obj->lastname);
printf("Podej cene: ");
gets(obj->price);
printf("Podaj opis usterki: ");
gets(obj->descreption);
strcat(notification.descreption,"\n");
if(fwrite(obj,sizeof(struct notification),1,fptr) != 1)
{
perror("Blad: ");
} else{
printf("Dane dodane poprawnie\n");
}
free(obj);
fclose(fptr);
}
Now ALL display and insert OK, but in file.txt I see Chinese characters, why?
There are a variety of problems in the readDatabase function
while(!feof)-is-always-wrong
the fread needs to be in the loop.
you don't need to malloc the memory, but if you do malloc memory, you should free it when you're done with it
you always need to check the return value from fopen, because it can and does fail, e.g. because the file is not found
With all that in mind, the readDatabase function should look like this
void readDatabase( void )
{
struct notification object2;
if ( (fptr = fopen("G:\\file.txt","rb")) == NULL )
{
printf( "File not found\n" );
return;
}
while ( fread( &object2, sizeof(struct notification), 1, fptr ) == 1 )
{
printf("Imie: %s\n", object2.name);
printf("Nazwisko: %s\n", object2.lastname);
printf("Cena: %s\n", object2.price);
printf("Opis: %s\n", object2.descreption);
printf("==========\n");
}
fclose(fptr);
}
Move this line:
fread(object2,sizeof(struct notification),1,fptr);
inside your while loop.
scanf("%d", &option); followed by gets() leads to trouble. The first does not consume the '\n' after the number and the second only reads in the short line '\n'.
Do not use scanf(). Do not use gets(). Use fgets(), then parse the input.
scanf() will leave new line character in input stream by default. you can use getchar() function to clear this new line character or you can flush the input buffer like this.
while ((ch = getchar()) != '\n' && ch != EOF);
but don't use fflush(stdin) because if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input. As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.