The code is supposed to Accept Data,Display the entire data stored till the current execution,Modify or make changes to the already accepted data.
WHAT IM LOOKING FOR IN AN ANSWER:how to write the code for a Modify module?
how to correct the Add or accept data,Display
data so they function perfectly.
#include<stdio.h>
typedef struct
{
int select;
char lastname[25];
char firstname[25];
char address[25];
int phonenumber[25];
} addressbook;
#define ARRAYLEN 2 //The lecturer told to use this "#define ARRAYLEN 2
addressbook a[ARRAYLEN]; //but why 2?and why use ARRAYLEN 2 with define
FILE *fp;
int main() //how is it affecting my program
{
int i;
int c;
int fgetc(FILE *stream);
int fputc(int c,FILE *stream);
fp = fopen("addressbook.dat","a+");
//ADD
for( i=0; i<ARRAYLEN ; ++i)
{
printf("enter details\n");
printf("enter lastname:\n");
scanf("%s", a[i].lastname);
printf("enter firstname:\n");
scanf("%s", a[i].firstname);
printf("enter address:\n");
scanf("%s", a[i].address);
printf("enter phone number:\n");
scanf("%d", a[i].phonenumber);
fwrite(&a[i], sizeof(a), 1, fp); /* notice, array indexed */
};
fclose(fp);
//DISPLAY
fopen("addressbook.dat", "r");
for(i=0; i<ARRAYLEN; ++i)
{
fread(&a[i], sizeof(a), 1, fp );
fgetc;
printf("first name is %s",a[i].firstname);
printf("last name is %s",a[i].lastname);
printf("the address is %s",a[i].address);
printf("the phonenumber is %d",a[i].phonenumber);
};
fclose(fp);
return 0;
}
IMPORTANT NOTE: I use a windows vista os and the compiler is Turbo C++
Related
I have a questions regarding the fread() and fwrite() function in c.
Talking about the first parameter void* If i am dealing with array of structure and want to pass an entire array what should i use &arrayName or arrayName.
Now I am trying to input some data from users create a student.txt file and store the data in that file and again read that data from the same file and display it.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
struct dob
{
int year,month,date;
};
struct student
{
int roll;
char name[20],address[20],faculty[30];
struct dob a;
};
struct student s1[2],s2[2];
FILE *fp;
fp = fopen("student.txt","w+b");
if(fp == NULL)
{
printf("Cannot open file");
exit(0);
}
for(int i = 0 ; i < 2 ; i++)
{
fflush(stdin);
printf("Enter the name of student %d\n",i+1);
scanf("%[^\n]s",s1[i].name);
fflush(stdin);
printf("Enter address\n");
scanf("%[^\n]s",s1[i].address);
fflush(stdin);
printf("Enter roll no\n");
scanf("%d",&s1[i].roll);
fflush(stdin);
printf("Enter faculty\n");
scanf("%[^\n]s",s1[i].faculty);
fflush(stdin);
printf("Enter the Birth year\n");
scanf("%d",&s1[i].a.year);
printf("Enter the Birth month\n");
scanf("%d",&s1[i].a.month);
printf("Enter the Birth date\n");
scanf("%d",&s1[i].a.date);
}
fwrite(&s1,sizeof(s1),2,fp);
rewind(fp);
fread(&s2,sizeof(s2),2,fp);
for(int i = 0 ; i < 2 ; i++)
{
printf("Name : %s\n Address = %s\n Faculty = %s\n Roll = %d\n year = %d\n month = %d\n date =
%d\n",
s2[i].name,s2[i].address,s2[i].faculty,s2[i].roll,s2[i].a.year,s2[i].a.month,s2[i].a.date);
}
fclose(fp);
return 0;
}
I am asking it because both of them works for my above code.But How?
I am talking about this line
fwrite(&s1,sizeof(s1),2,fp);
fread(&s2,sizeof(s2),2,fp);
Here s1 and s2 works without & as well
So i basically have a binary input folder containing some students and their information. And i don't understand some things regarding the fseek and fread there after "while" function. After i run it, and type a key to search for a student, it prints the student associated with that key instead of the one on that position (dimension in bytes from the origin as offset). And i want to know why, in order to use the information to my project, as this program is a kind of tutorial from the professor. Thank you in advance!
*EDIT ( Second program is my attempt for the project, but with cars. Its output is the car on position "chooseKey" and not with "chooseKey" as an atribute, as the first program. And i don t know what i did wrong.)
#include <stdio.h>
#include <conio.h>
typedef struct {
int nrm;
char CNP[14];
char nume[30];
int an;
int grupa;
unsigned char note[20];
char is;
} STUDENT;
int filesize(FILE* f, int rec_size)
{
long crt_pos;
int size;
crt_pos = ftell(f);
fseek(f, 0, SEEK_END) ;
size=ftell(f) / rec_size;
fseek(f, crt_pos, SEEK_SET);
return size;
}
void main()
{ char numefr[30] = "Studenti_r_f.dat";
FILE* f;
STUDENT x;
int key, dim;
fopen_s(&f, numefr, "rb+");
dim=filesize(f, sizeof(STUDENT));
printf_s("Enrollment number: ");
scanf_s("%d", &key);
while(key != 0)
{
//check key range
if(key >= dim)
printf_s("\nThere is no student with this enrollment number. Try again?");
else
{
//check if valid key
fseek(f, key*sizeof(STUDENT), SEEK_SET);
fread(&x, sizeof(STUDENT), 1, f);
if(x.is == 0)
printf("\nThere is no student with this enrollment number. Try again?");
else
printf_s("\nStudent: %s, Year: %d, Group: %d, ATP grade: %d\n",x.nume,x.an,x.grupa,x.note[5]);
}
printf_s("\n\nEnrollment number (or 0): ");
scanf_s("%d", &key);
}
fclose(f);
printf("\nDone. Press a key.",numefr);
_getch();
}
typedef struct {
int key;
char color[20];
int price;
char brand[15];
}CAR ;
int sizeOfFile(FILE* inBinFile, int sizeOfRecord)
{
long currentPosition;
int size;
currentPosition = ftell(inBinFile);
fseek(inBinFile, 0, SEEK_END);
size = ftell(inBinFile) / sizeOfRecord;
fseek(inBinFile, currentPosition, SEEK_SET);
return size;
}
void main()
{
FILE * inBinFile;
CAR var;
int chooseKey, fileDim;
printf_s("Type a key to identify a car..."); // 20 records in the file
scanf_s("%d", &chooseKey);
fopen_s(&inBinFile, "Machines.bin", "rb+");
fileDim = sizeOfFile(inBinFile, sizeof(CAR));
while (chooseKey != -1)
{
if (chooseKey >= fileDim)
printf_s("\nNo car with key %d found. Retry.", chooseKey);
else
{
fseek(inBinFile, chooseKey*sizeof(CAR), SEEK_SET);
fread(&var, sizeof(CAR), 1, inBinFile);
printf_s("\nThe %d key indicates to the %s car coloured in %s which cost %d dollars", chooseKey, var.brand, var.color, var.price);
}
printf_s("\n\n\nTo search for another car enter a key, or hit 1 and enter to stop: ");
scanf("%d", &chooseKey);
}
fclose(inBinFile);
printf_s("\nAlright. Press any key...");
_getch();
} ```
I'm wondering if I could use fseek() on editing the value of a variable on a file. All the tutorials I saw online were about editing a text, but how can I use fseek() to edit a value.
Here's how my program works: The user inputs a name, gender, and age. The user can input as many data as they want. Now, the user searches a name; and the gender, and age of that name will display. The user is then prompted to edit the age. After inputting a new age, the file will now be edited, with the new age written.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct data
{
char name[30];
char gender[10];
int age;
};
int main(void)
{
struct data client;
FILE* fp;
char ch = 0;
do
{
printf("Enter Name: ");
scanf("%s", client.name);
printf("Enter Gender: ");
scanf("%s", client.gender);
printf("Enter Age: ");
scanf("%d", &client.age);
fp = fopen("data.txt", "ab");
fwrite(&client, sizeof(client), 1, fp);
fclose(fp);
printf("continue? \n");
scanf(" %c", &ch);
} while (ch != 'n'); // continuously appends file till letter n is read;
char input[30]; // user input
printf("name?\n");
scanf("%s", input);
struct data Read;
fp = fopen("data.txt", "rb");
int newAge;
while (fread(&client, sizeof(client), 1, fp))
{
if (strcmp(client.name, input) == 0) // compare variable with user input
{
printf("%s", client.name);
printf(" %s", client.gender);
printf(" %d y/o", client.age);
printf("\n");
printf("enter new age");
scanf("%d", &newAge);
//fseek function
}
}
return 0;
}
Hope somebody can help.
I have a test tomorrow and files confuse me a lot. This code I wrote stops at fscanf(f1, "%d", &n); and does not take any input in. I followed the teacher's example when coding this. Does any one have any idea why this happens? Also, is F2 completely necessary? The teacher's practice questions say to open up the file in read, read everything, keep a running total of all the wages earned, then once the reading is complete, prompt for an output filename string, open it, and write to the average value of all the earnings. I understand fprintf and fscanf to an extent, and the difference between read and write mode, however, I do not understand why F2 is necessary? He uses F2 in a similar example that used different variable names. Thanks in advance.
#include <stdio.h>
int main(){
FILE *f1;
FILE *f2;
char name[30];
char name2[30];
float wage;
float wage_total;
int n;
int SSN;
printf("What is the file name?\n");
scanf("%s", name);
f1 = fopen(name, "r");
printf("What is the file name for F2?\n");
scanf("%s", name2);
f2 = fopen(name2,"w");
int i;
wage = 0;
fscanf(f1, "%d", &n);
for(i = 0; i < n; i++){
fscanf(f1,"%d", &SSN);
fscanf(f1, "%f", &wage);
wage_total += wage;
}
fprintf(f2,"%f", wage_total);
fclose(f1);
fclose(f2);
system("pause");
return 0;
}
Teacher's Example:
#include <stdio.h>
int main() {
FILE* fp1;
FILE* fp2;
int n;
int i;
int id,len,width;char word[30],word2[30];
printf("type input fname:");
scanf("%s",word);
printf("type output fname:");
scanf("%s",word2);
fp1 = fopen(word, "r");
fp2 = fopen(word2,"w");
fscanf(fp1,"%d", &n);
for(i=0;i<n;i++)
{ fscanf(fp1,"%d%d%d", &id, &len, &width);
if ( (len*width) > 500)
printf("%d %d %d", id, len, width);
}
fclose(fp1);
fclose(fp2);
system("pause"); return 0;
}
My program scans names and birth years and stores them in an array of structures. Scanning from keyboard and printing in screen works fine, but I'm not sure whether printing in my binary file is correct because my program runs without errors and I can't check if the data has been printed correctly in the binary file.
My question is about whether the syntax of my "fwrite" functions is correct.
#include <stdio.h>
#define MAXNAME 50 //size of name
#define MAXPERSONS 2 //Max num of persons
typedef struct{
char name[MAXNAME];
int year;
}person_t;
int read_person(person_t[], int);//scans the person
int write_person(const person_t[], int, FILE*);//prints the persons in the screen and the bfile
int main()
{
FILE *pfile;
person_t v[3];
int iscan=0,iprint;
if((pfile=fopen("persons.bin","wb"))==NULL) printf("couldnt open<vehicles.txt>\n");
else{
while(iscan<MAXPERSONS){
read_person(&v[iscan],iscan+1);
iscan++;
}
for(iprint=0;iprint<iscan;iprint++)
write_person(&v[iprint],iprint+1,pfile);
}
fclose(pfile);
printf("\n\n");
return 0;
}
int read_person(person_t v[],int i)
{
printf("Person %d",i);
printf("\n\tName: ");
fflush(stdin);
gets(v->name);
printf("\n\tYear: ");
scanf("%d",&v->year);
}
int write_person(const person_t v[],int j, FILE *pfile)
{
//print in screen
printf("\nPerson %d",j);
printf("\n\tName: %s\n",v->name);
printf("\n\tYear: %d\n",v->year);
//print in the binary file
fwrite(v->name,sizeof(char),1,pfile);
fwrite(&v->year,sizeof(int),1,pfile);
}
This program reads from the bin file
#include<stdio.h>
#define MAXNAME 50 //size of name
#define MAXPERSONS 2 //Max num of persons
typedef struct{
char name[MAXNAME];
int year;
}person_t;
int read_person(person_t[], int, FILE*);
int write_person(const person_t[], int);
int main(){
FILE *pfile;
person_t v[3];
int iscan=0,iprint;
if((pfile=fopen("persons.bin","rb"))==NULL) printf("couldnt open<vehicles.txt>\n");
else{
while(iscan<MAXPERSONS){
read_person(&v[iscan],iscan+1,pfile);
iscan++;
}
for(iprint=0;iprint<iscan;iprint++)
write_person(&v[iprint],iprint+1);
}
fclose(pfile);
printf("\n\n");
return 0;
}
int read_person(person_t v[],int i, FILE *pfile){
//read from the binary file
fread(v->name, sizeof(v->name),1,pfile);
fread(&v->year,sizeof(v->year),1,pfile);
}
int write_person(const person_t v[],int j){
//print in screen
printf("\nPerson %d",j);
printf("\n\tName: %s\n",v->name);
printf("\n\tYear: %d\n",v->year);
}
Suggest changing fwite() to write the full size of person_t.
int write_person(const person_t v[], int j, FILE *pfile) {
//print in screen
printf("\nPerson %d",j);
printf("\n\tName: %s\n",v[j].name);
printf("\n\tYear: %d\n",v[j].year);
//print in the binary file
if (1 != fwrite(&v[j], sizeof(v[j]),1, pfile)) handle_error();
return 0;
}
int read_person(person_t v[], int i) {
printf("Person %d",i);
printf("\n\tName: ");
// don't do this fflush(stdin);
// consider scanf() gets(v.name);
// " %49[^\n]": space to consume leading whitespace, 49 (50 -1 ) limit input, [^\n] to read any text but \n
if (1 != scanf(" %49[\n]", v[i].name)) handle_error();
printf("\n\tYear: ");
if (1 != scanf("%d",&v[i].year)) handle_error();
return 0;
}
You might consider writing and reading the entire person_t struct.
int write_person(const person_t v[],int j, FILE *pfile)
{
//print in screen
printf("\nPerson %d",j);
printf("\n\tName: %s\n",v[j].name);
printf("\n\tYear: %d\n",v[j].year);
fwrite(&(v[j]),sizeof(person_t),1,pfile);
}
The general idea you are approaching is called 'serialization' or 'marshalling' (depending upon author). There are many ways serialize or marshall data, but some good approaches are JSON, UBJSON, MessagePack, and ProtocolBuffers, among others.