input of data in a FILE - c

i have to input the data into a FILE * (this is in C and using codeblocks), the data is a struct containing 3 char[ ] an 1 double, i dont know why when i print the file it repeats the last struct twice and in "dni" it puts 0.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char dni[9];
char nombre[100], apellido[100];
double monto_adeudado;
} t_datos;
void carga_del_archivo(char[]);
t_datos carga_struct(t_datos);
int main()
{
char nombrearchivo[30];
printf("ingrese el nombre del archivo: ");
gets(nombrearchivo);
carga_del_archivo(nombrearchivo);
return 0;
}
void carga_del_archivo(char nombre[30])
{
FILE* ptrarch;
t_datos aux;
ptrarch = fopen(nombre, "ab");
if (ptrarch != NULL) {
do {
aux = carga_struct(aux);
fwrite(&aux, sizeof(t_datos), 1, ptrarch);
} while (strcmp(aux.dni, "0") != 0);
} else {
printf("ERROR\n");
}
}
t_datos carga_struct(t_datos aux)
{
printf("\ningrese el dni: ");
fflush(stdin);
gets(aux.dni);
if (strcmp(aux.dni, "0") == 0)
return aux;
printf("\ningrese el nombre: ");
fflush(stdin);
gets(aux.nombre);
fflush(stdin);
printf("\ningrese el apellido: ");
gets(aux.apellido);
fflush(stdin);
printf("\ningrese el monto adeudado: ");
scanf("%lf", &aux.monto_adeudado);
return aux;
}

Problem is here:
{
aux=carga_struct(aux);
fwrite(&aux,sizeof(t_datos),1,ptrarch);
}while(strcmp(aux.dni,"0")!=0);
When you enter 0 here aux=carga_struct(aux) you write it to the disk by fwrite on next line before checking this statement: while(strcmp(aux.dni,"0")!=0).

Related

Reading from binary file LANG C

I am having trouble reading from a bin file.
I am recording some text in binary (correctly i think), but my code isn't able to read the text I wrote and print it in the console. When i open the file the information is there (this document is use to storage the information from the client and the login access) and i can login, but when i try to read and print in console it doesn't show me.
I am using a struct to get the values from the document, and then i open the document "fopen()" but when i try to read with the "fread()" in a "while" I don't get in, the print don't give me the right information
I try to reduce as much i could of the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <dir.h>
#include <unistd.h>
#include <time.h>
#include <conio.h>
#define SIZE 1000
typedef struct
{
char id[10];
char nome[100];
char passe[100];
}Pacient;
Pacient p1;
FILE* filepaciente;
//variables
char tmpnome[100], tmppassword[100];
//variable for path
char nomedoc[15];
char pasta[250];
char sessionName[15];
char tmp_name[15];
char fullpath[200];
char tmp_nome[15];
void vedocumento(int* i, char* line, char pacienteData[])
{
// DEFINE A VARIÁVEL USERDATA COMO UMA STRING VAZIA
strcpy(pacienteData, "");
// IF FINDS "|", GO TO THE NEXT CHARACTER
if (line[*i] == '|')
{
(*i)++;
}
//WHEN THE CHARACTER IS DIFERENT THEN |, ADD THAT CHARACTER TO THE ARRAY USERDATA
while (line[*i] != '|') // *i = 0
{
strncat(pacienteData, &line[*i], 1); // userData = "" ; userData = userData + carater
(*i)++;
}
}
findpath()
{
//PROCURA O CAMINHO ONDE SE ENCONTRA O PROJETO
if (getcwd(pasta, sizeof(pasta)) == NULL)
{
printf("ERROR!\n");
}
else
{
strcat(pasta, "\\file\\");
//CRIA O FICHEIRO COM O NUMERO DE INTERNO
strcpy(nomedoc, strcat(tmp_nome, ".bin"));
//JUNTA O CAMINHO COMPLETO AO NOME DO FICHEIRO
strcat(pasta, nomedoc);
strcpy(fullpath, pasta);
}
}
int main() //where i write in the bin file
{
//GETTING REGISTRY DATA
fflush(stdin); //para ir so buscar os dados
printf("\nName pacient: ");
scanf("%[^\n]", p1.nome);
printf("\nPassword do pacient %s: ", p1.nome);
scanf("%s", p1.passe);
printf("\nID pacient %s: ", p1.nome);
scanf(" %s", p1.id);
strcpy(tmp_nome, p1.nome);
strcpy(tmp_nome, strlwr(tmp_nome));
findpath();
if (access(fullpath, F_OK) == 0)
{
//IF EXISTS
printf("Este nome de utilizador já foi registado! Por favor, tente novamente!\n");
}
else
{
// IF DOESN'T EXIST
filepaciente = fopen(fullpath, "wb");
if (filepaciente == NULL)
{
printf("\nerror\n");
}
//size_t elements_written = fwrite(&p1, sizeof(Paciente), 1, filepaciente);
//PRINTING ON FILE
fprintf(filepaciente, "%s|%s|%s\n", p1.nome, p1.passe, p1.id);
fclose(filepaciente);
}
//WHERE I WANT TO PRINT ON THE CONSOLE
{
printf("Name do pacient: ");
scanf(" %[^\n]", tmpnome);
strcpy(tmp_nome, tmpnome);
strcpy(tmp_nome, strlwr(tmp_nome));//this is to get the name of the document
findpath(); //Find the path to the document
if (access(fullpath, F_OK) == 0)
{
filepaciente = fopen(fullpath, "rb"); //Open the document
Pacient pacient[100];
char line[SIZE];
int nline = 0;
fgets(line, SIZE, filepaciente);
int i = 0;
vedocumento(&i, line, pacient[nline].nome);
vedocumento(&i, line, pacient[nline].passe);
nline++;
//LOOP TO CHECK
for (i = 0; i < 1; i++)
{
if (strcmp(tmpnome, pacient[i].nome) == 0)
{ //WRITE INFO
char buf[SIZE];
if (filepaciente == NULL)
{
printf("\nERRO OPENING\n");
}else printf("\nOPEN THE FILE\n");
//IF I PUT "==1" DON'T GET IN THE WHILE
while( fread(&p1, sizeof(p1), 1, filepaciente) == 1)
{
printf("%c", p1); //NOT SURE IF THIS IS CORRECT
}
}
}
}
}
}

Double chained list problems passing char[] with function

I have been working on a school project that requires working with double-chained list with struct. I have managed to create the functions that add an integer and a char to the struct. But when I attempt to add the char it wont works, but with the integer, works fine.I'm working with 3 files, the header.h, function.c, and main.c
main.c file:
No* primeiro = NULL;
No* atual = NULL;
int i, val;
char tecla;
char nome[50];
for(i = 0; i < 3; i++)
{
printf("Digite o valor: ");
scanf("%d", &val);
getchar();
printf("\nType something: ");
fgets(nome, 50, stdin);
inserir_final(&primeiro, val, nome);
}
The function file:
struct no{
int elemento;
char nome[50];
struct no *anterior;
struct no *proximo;
};
void inserir_final (No **primeiro, int valor, char nome[]){
No* novo = novo_no(valor, nome);
No* aux;
if(*primeiro == NULL){
*primeiro = novo;
}
else
{
novo->proximo = *primeiro;
(*primeiro)->anterior->proximo = novo;
novo->anterior=(*primeiro)->anterior;
(*primeiro)->anterior = novo;
}
}
No* novo_no(int dado, char nome[]){
No* aux = (No*)malloc(sizeof(No));
aux->elemento = dado;
strcpy(aux->nome, nome);
aux->proximo = aux;
aux->anterior = aux;
return aux;
}
This is how I print it:
void listar_nos(No* primeiro){
No* aux = primeiro;
printf("Listagem do primeiro ao ultimo: \n");
if (primeiro == NULL)
return;
do
{
printf("Elemento: %d\n", aux->elemento);
printf("Nome: %s\n", aux->nome);
aux = aux->proximo;
} while (aux != primeiro);
printf("\n\nListagem do ultimo ao primeiro: \n");
aux = aux->anterior;
do
{
printf("Elemento: %d\n", aux->elemento);
aux=aux->anterior;
} while (aux->proximo!=primeiro);
}
The output:
Digite o valor: 10
Type something: ola
Digite o valor: 20
Type something: ok
Digite o valor: 30
Type something: po
Digite p para proximo e A para anteriro:s
Todos os nos: Listagem do primeiro ao ultimo:
Elemento: 10
Nome: ñ
Elemento: 20
Nome: ▄
Elemento: 30
Nome: $
An array is passed to a function as a pointer. You are printing the numerical value of the pointer. To print the string, you want to use %s, not %d.

Exception thrown at 0x7C43F338 (ucrtbased.dll)

the teacher gives me a code, I try to run it on visual basic 2019 but get Exception thrown at 0x7C43F338 (ucrtbased.dll).
I'm just introduced to c and have no clue what's wrong
here my code :
#include <cstdio>
#include <malloc.h>
#include <string.h>
//percobaan 1 dan 3
int main(){
printf("percobaan 1 dan 3\n");
struct dtnilai
{
char nrp[10];
char nama[20];
double nilai;
struct dtnilai* next;
};
struct dtnilai* ujung;
void sisip_awal_LIFO();
{
struct dtnilai* tampung = 0;
int j = 0; char jawab[2];
while (1)
{
ujung = (struct dtnilai*)malloc(sizeof(struct dtnilai));
fflush(stdin);
printf("NRP :"); scanf("%s", &ujung->nrp);
printf("Nama :"); scanf("%s", &ujung->nama);
printf("Nilai Test :"); scanf("%lf", &ujung->nilai);
if (j == 0)
{
ujung->next = NULL;
tampung = ujung;
}
else
{
ujung->next = tampung;
tampung = ujung;
}
printf("Ada data lagi(y/t):"); scanf("%s", &jawab);
if ((strcmp(jawab, "Y") == 0) || (strcmp(jawab, "y") == 0))
{
j++; continue;
}
else if ((strcmp(jawab, "T") == 0) || (strcmp(jawab, "t") == 0))
break;
}
}
void tampil_list();
{
struct dtnilai* tampil;
printf("Data Mahasiswa yang telah diinputkan :\n");
printf("NRP\tNama\tNilai\n");
tampil = ujung;
while (tampil != NULL)
{
printf("%s\t%s\t%6.2f\n", tampil->nrp, tampil->nama,
tampil->nilai);
tampil = tampil->next;
}
}
void sisip_stl_simpul();
{
struct dtnilai* sisip; struct dtnilai* stl;
char cari[20];
char nrp[10];
char nama[20];
double nilai;
struct dtnilai* next;
if (ujung == NULL)
printf("List Belum Terbentuk. Buatlah Dulu!");
else
{
ujung = (struct dtnilai*)malloc(sizeof(struct dtnilai));
sisip = (struct dtnilai*)malloc(sizeof(struct dtnilai));
printf("Masukkan Data Yang Akan Disisipkan \n");
printf("NRP :\n"); gets_s(sisip->nrp); //<- cant input
printf("Nama :\n"); gets_s(sisip->nama);
printf("Nilai Test :\n"); (sisip->nilai); //<-cant input
printf("Data disisipkan setelah data ? (nama) : ");
gets_s(cari);
//gets_s(cari);
stl = ujung;
while(strcmp(stl->nama, cari) != 0) //<- error
{
stl = stl->next;
}
sisip->next = stl->next;
stl->next = sisip;
}
}
void tampil_list();
{
struct dtnilai* tampil;
printf("Data Mahasiswa yang telah diinputkan :\n");
printf("NRP\tNama\tNilai\n");
tampil = ujung;
while (tampil != NULL)
{
printf("%s\t%s\t%6.2f\n", tampil->nrp, tampil->nama,
tampil->nilai);
tampil = tampil->next;
}
}
}
on this line
printf("NRP :\n"); gets_s(sisip->nrp); //<- cant input
printf("Nama :\n"); gets_s(sisip->nama);
printf("Nilai Test :\n"); (sisip->nilai); //<-cant input, also if i put gets_s in here i get error.
printf("Data disisipkan setelah data ? (nama) : ");
gets_s(cari);
the original was for gets_s was "gets" but "gets" get identifier is undefined, I also try with fgets, scanf but it just didn't work
sorry for my English.

How to use Binary Search on array of string

I have to write a program only using things that i've learned in class, where I register information from a car, sort it and use the Binary Search to search for a cars' license plate. If the license plate is found, print all the info about that especific car, If don't pritnt "Not found" and returns -1. All works fine until the Binary Search, the problem is that it won't find the license plate, It always returns -1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CARRO 5 // DEFINE TAMANHO DA STRUCT
typedef struct // STRUCT
{
char placa[50];
char marca[50];
char modelo[50];
char ano[50];
char valordiaria[50];
} carro;
carro car[MAX_CARRO];
int compare (const void * a, const void * b)
{
carro *carroA = (carro *)a;
carro *carroB = (carro *)b;
return strcmp(carroA, carroB);
}
int main()
{
int x=0; //COUNTER
for(x=0; x<MAX_CARRO; x++) // CAR REGISTER
{
printf("\nCarro: %d", (x+1));
printf("\nPlaca: ");
scanf("%s",car[x].placa);
printf("Marca: ");
scanf("%s",car[x].marca);
printf("Modelo: ");
scanf("%s",car[x].modelo);
printf("Ano: ");
scanf("%s",car[x].ano);
printf("Valor da diaria: ");
scanf("%s",car[x].valordiaria);
}
qsort (car, MAX_CARRO, sizeof(carro), compare); // USO DO QSORT
printf("\n\nSTRUCT ORDENADA: \n");
for(x=0; x<MAX_CARRO; x++) // MOSTRA NA TELA A STRUCT ORDENADA
{
printf("\n\n\nCarro: %d", (x+1));
printf("\nPlaca: %s", car[x].placa);
printf("\nMarca: %s", car[x].marca);
printf("\nModelo: %s", car[x].modelo);
printf("\nAno: %s", car[x].ano);
printf("\nValor da diaria: %s", car[x].valordiaria);
}
char k[10];
// *****BINARY SEARCH******
printf("\n\n\n*****BUSCA DE PLACAS*****\n\n\n\n");
printf("Digite a placa que deseja procurar: \n");
scanf("%s", &k);
// ***PROBLEM***
int low, high, mid;
low=0;
high = MAX_CARRO-1;
while(low<=high)
{
mid = (low+high)/2;
if (strcmp(k, car[mid].placa)<0)
high=mid-1;
else if (strcmp(k, car[mid].placa)>0)
low=mid+1;
else
{
printf("\nPlaca: %s", car[mid].placa);
printf("\nMarca: %s", car[mid].marca);
printf("\nModelo: %s", car[mid].modelo);
printf("\nAno: %s", car[mid].ano);
printf("\nValor da diaria: %s", car[mid].valordiaria);
}
printf("\n\n****Not found****\n\n\n");
return -1; //
}
}
You have few bugs.
First one is in your compare() function. You can not write this line
return strcmp(carroA, carroB);
Because strcmp is working just with char* types, and carroA and carroB are of type carro*. You should place
return strcmp(carroA->placo, carroB->placo);
Now you will sort your structures by the value of placo.
Now lets take a look at your main function.
First bug in main() is in your line of code
scanf("%s", &k);
You don't need &, you should make it like this
scanf("%s",k);
Second bug is in your while() loop in the last line
return -1;
This is a huge thing because main() will return -1. If you want main() to exit like an error occurred you should write return 1;
Maybe you should use one variable to determine weather you have found what you was looking for in your binary search
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CARRO 5 // DEFINE TAMANHO DA STRUCT
typedef struct // STRUCT
{
char placa[50];
char marca[50];
char modelo[50];
char ano[50];
char valordiaria[50];
} carro;
carro car[MAX_CARRO];
int compare (const void * a, const void * b)
{
carro *carroA = (carro *)a;
carro *carroB = (carro *)b;
return strcmp(carroA->placa, carroB->placa);
}
int main()
{
int x=0; //COUNTER
for(x=0; x<MAX_CARRO; x++) // CAR REGISTER
{
printf("\nCarro: %d", (x+1));
printf("\nPlaca: ");
scanf("%s",car[x].placa);
printf("Marca: ");
scanf("%s",car[x].marca);
printf("Modelo: ");
scanf("%s",car[x].modelo);
printf("Ano: ");
scanf("%s",car[x].ano);
printf("Valor da diaria: ");
scanf("%s",car[x].valordiaria);
}
qsort (car, MAX_CARRO, sizeof(carro), compare); // USO DO QSORT
printf("\n\nSTRUCT ORDENADA: \n");
for(x=0; x<MAX_CARRO; x++) // MOSTRA NA TELA A STRUCT ORDENADA
{
printf("\n\n\nCarro: %d", (x+1));
printf("\nPlaca: %s", car[x].placa);
printf("\nMarca: %s", car[x].marca);
printf("\nModelo: %s", car[x].modelo);
printf("\nAno: %s", car[x].ano);
printf("\nValor da diaria: %s", car[x].valordiaria);
}
char k[10];
// *****BINARY SEARCH******
printf("\n\n\n*****BUSCA DE PLACAS*****\n\n\n\n");
printf("Digite a placa que deseja procurar: \n");
scanf("%s", k);
// ***PROBLEM***
int low, high, mid;
low=0;
high = MAX_CARRO-1;
int found=0;
while(low<=high && !found)
{
mid = (low+high)/2;
if (strcmp(k, car[mid].placa)<0)
high=mid-1;
else if (strcmp(k, car[mid].placa)>0)
low=mid+1;
else
{
found = 1;
printf("\nPlaca: %s", car[mid].placa);
printf("\nMarca: %s", car[mid].marca);
printf("\nModelo: %s", car[mid].modelo);
printf("\nAno: %s", car[mid].ano);
printf("\nValor da diaria: %s", car[mid].valordiaria);
}
}
if(!found)
printf("\n\n****Not found****\n\n\n");
return 0; //
}

Bug fix for Dog Database

I am working on a dog database and have one bug I cannot figure out.
The bug is: Thread 1: signal SIGABRT.
Every time I try to search or change for a dog, I get this error code.
My code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SZ_NAME 32
#define SZ_BREED 32
#define SZ_COLOR 16
#define SZ_SEX 8
struct dog_entry
{
char name [SZ_NAME];
char breed [SZ_BREED];
char color [SZ_COLOR];
float weight;
int age;
char sex [SZ_SEX];
};
#define REC_SIZE sizeof(struct dog_entry)
struct dog_entry record[REC_SIZE];
char pr_menu(void);
void addRecord(struct dog_entry *reg, int type);
void modifyRecord(int);
void delete_dog(int g, struct dog_entry *rec);
void view_dog(int, struct dog_entry *reg);
int find_dog(int, struct dog_entry *rec);
void searchRecord(int, struct dog_entry *rec);
int main()
{
struct dog_entry reg;
int i = 0, n;
while(free)
{
char ch = pr_menu();
switch(ch)
{
case '1':
addRecord(&reg, 1);
i++;
break;
case '2':
addRecord(&reg, 2);
break;
case '3': delete_dog(1, &reg);
break;
case '4': view_dog(1, &reg);
break;
case '5': searchRecord(n, &reg);
break;
default: break;
}
if (ch == '6') // exit
break;
}
// system("pause");
}
char pr_menu(void)
{
char ch;
// system("cls");
printf("\n Menu:\n 1.Add\n 2.Change\n 3.Delete\n 4.View\n 5.Search\n 6.Exit\n \nEnter Choice: ");
scanf("%c", &ch);
return ch;
}
//Function that adds a record
void addRecord(struct dog_entry *rec, int type)
{
FILE * f;//define donde se guarda el archivo
f = fopen("database_dog.txt", "w+");//definition of file
// system("cls");
printf("Add the Dog: ");
printf("\n Enter Name: ");
scanf("%s", rec->name);
printf("\n Enter Breed: ");
scanf("%s", rec->breed);
printf("\n Enter Color: ");
scanf("%s", rec->color);
printf("\n Enter Weight: ");
scanf("%f", &rec->weight);
printf("\n Enter Age: ");
scanf("%d", &rec->age);
printf("\n Enter Sex: ");
scanf("%s", rec->sex);
fseek(f, 0, SEEK_END);
fwrite(&rec, sizeof(struct dog_entry), 1, f);//save the data
fclose(f);//close the file
printf("\n\n");
// system("pause");
}
//Function that modifies the record
void modifyRecord(int index)
{
}
//Function that displays records
void view_dog(int total, struct dog_entry *rec)
{
FILE * f;//define donde se guarda el archivo
f = fopen("database_dog.txt", "r+");//definition of file
char name [SZ_NAME];
// system("cls");
printf("View the Dog: ");
printf("\n Enter Dog's Name: ");
scanf("%s", name);
rewind(f);
while(fread(&rec, sizeof(struct dog_entry), 1, f))
{ //apertura del while
if(strcmp(name, rec->name) == 0)//compara una cadena de caracteres
{
printf("\n Name: %s", rec->name);
printf("\n Breed: %s", rec->breed);
printf("\n Color: %s", rec->color);
printf("\n Weight: %f", rec->weight);
printf("\n Age: %d", rec->age);
printf("\n Sex: %s", rec->sex);
printf("\n\n");
// system("pause");
break;
}
}
fclose(f);//close the file
}
int find_dog(int g, struct dog_entry *rec){
FILE * f;//define donde se guarda el archivo
f = fopen("database_dog.txt", "r+");//definition of file
char name [SZ_NAME];
printf("\n Enter Dog's Name: ");
scanf("%s", name);
rewind(f);
int c;
while(fread(&rec, sizeof(struct dog_entry), 1, f))
{ //apertura del while
if(strcmp(name, rec->name) == 0)//compara una cadena de caracteres
{
c++;
break;
}
}
fclose(f);//close the file
return c;
}
void delete_dog(int g, struct dog_entry *rec){
FILE * f;//define donde se guarda el archivo
f = fopen("database_dog.txt", "r+");//definition of file
char name [SZ_NAME];
int num = 0;
// system("cls");
printf("Delete Record: ");
printf("\n Enter Dog's number: ");
scanf("%d", &num);
fseek(f, num * sizeof(struct dog_entry), SEEK_SET);
fread(&rec, sizeof(struct dog_entry), 1, f);
fclose(f);//close the file
}
//Function that searches for the record
void searchRecord(int n, struct dog_entry *rec)
{
char dog[SZ_NAME];
int j;
int flag = 0;
flag = find_dog(0, rec);
if(flag == 1)
printf("Record exists\n");
else
printf("No such record exists\n");
}
In find_dog() on line 161:
fread(&rec, sizeof(struct dog_entry), 1, f);
rec is already a pointer, so you shouldn't take its address.
You've got the same problem in view_dog() on line 126.
I found this out by running a program called Valgrind, which you should definitely get and learn how to use if you are a C programmer.

Resources