How do I create a list with numbers read from a file? I can't seem to understand how to do that, because I don't know how many numbers the sequence contains, so how am I supposed to know how many nodes my list has to be composed of.
Here is the code I wrote: does the fgets command create a full list or it just fills the first node?
#include <stdio.h>
#include <stdlib.h>
int Sequenza (fp f1, fp f2, fp f3);
typedef FILE* fp;
typedef struct Nd{
int dato;
struct Nd* next;
} Nodo;
typedef Nodo* lista;
int Sequenza (fp f1, fp f2, fp f3){
lista seq1, seq2;
seq1 = malloc (sizeof(Nodo));
seq2 = malloc (sizeof(Nodo));
f1 = fopen ("sequenza1.txt", "r");
f2 = fopen ("sequenza2.txt", "r");
if (f1 == NULL || f2 == NULL){
printf ("Errore nell'apertura di uno dei due file\n");
return 0;
} else {
while (!feof(f1) && !feof(f2)){
fgets (seq1, MAX, f1);
fgets (seq2, MAX, f2);
}
}
fclose (f1);
fclose (f2);
}
I'm not sure that fgets creates a full list, but just fills in the first node.
Related
I'm trying to read a file and put the values in a Struct to sort then, but my code isn't working.
#include <stdio.h>
#include <stdlib.h>
struct person
{
char Nome[50];
int Idade;
double Altura;
};
int main ()
{
FILE *infile;
struct person input;
infile = fopen ("pessoas.txt", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
while(fread(&input, sizeof(struct person), 1, infile))
printf ("Nome = %s Idade = %d Altura = %f\n", input.Nome,
input.Idade, input.Altura);
// close file
fclose (infile);
return 0;
}
My file is:
Maria
15
1.6
Joao
21
1.8
Abel
23
1.7
Joana
40
1.6
You can use fscanf() to read file & populate the structure.
#include <stdio.h>
#include <stdlib.h>
struct person
{
char Nome[50];
int Idade;
double Altura;
};
int main ()
{
FILE *infile;
struct person input;
infile = fopen ("pessoas.txt", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
while(3 != fscanf(infile, "%49s %d %lf", input.Nome, &input.Idade, &input.Altura))
printf ("Nome = %s Idade = %d Altura = %lf\n", input.Nome, input.Idade, input.Altura);
// close file
fclose (infile);
return 0;
}
Create a function to read a text file and transfer their name to a dynamic vector of structures.
I'm reading the file but it doesn't appear nothing on the screen.
typedef struct aluno student;
struct aluno{
char name[50], address[50], number[9];
int year;enter code here
};
student *lerFicheiroTexto(char *nameFile, int *tam){
FILE *f1;
student buffer;
student *aux;
student *vetor = NULL;
f1 = fopen(nameFile, "rt");
if(f1 == NULL){
printf("Error opening the file text");
return NULL;
}
while(fscanf(f1, "%s %s %d %s", buffer.name, buffer.address, &buffer.year, buffer.number) == 3){
printf("%s\t%s\n%d\n%s\n", buffer.name, buffer.address, buffer.year, buffer.number);
aux = realloc(vetor, sizeof(student)*(*tam+1));
if(aux == NULL){
//realocation failled
printf("Reallocation failled. Maintain tam \n");
(*tam) = 0;
return NULL;
}
else{
vetor = aux;
vetor[(*tam)] = buffer;
}
(*tam)++;
}
fclose(f1);
return vetor;
}
I would need to have your input file to test this but I changed your code a bit.
I'm also a student so my apologies if I've done something wrong.
From what I see, I believe your code could be improved like so:
Definition of struct:
typedef struct aluno {
char name[50], address[50], number[9];
int year;
} Aluno;
Function to read the file and build your array:
Aluno* lerFicheiroTexto(char* nameFile, int tamanho)
{
FILE* file = fopen(nameFile, "r");
if (file == NULL) {
printf("Error opening the file text");
return NULL;
}
Aluno* listaAlunos = malloc(sizeof(Aluno));
char line[255];
while (fgets(line, 255, file) != NULL) {
Aluno currAluno;
sscanf(line, "%s %s %d %s", currAluno.name, currAluno.address, currAluno.year, currAluno.number);
listaAlunos[tamanho] = currAluno;
listaAlunos = realloc(listaAlunos, sizeof(Aluno) * ++tamanho);
}
fclose(file);
return listaAlunos;
}
Im having a hard time inputting the data to the file, whenever I input data to struct array then saves it to text file, fwrite() prints nothing to the file.
int last;
struct Person{
int pid;
char lname[MAXchar], fname[MAXchar], mname[MAXchar];
int age;
char subject[MAXchar];
float grade;
};
struct Person Num[MAX];
struct Person *No;
and this is how I save it to the text file.
void saveDATA(){
FILE *fp;
fp=fopen("database.txt","ab");
fwrite(No, sizeof(struct Person), 1, fp);
if(fwrite != 0)
printf("Success!\n");
else
printf("error!\n");
fclose(fp);
}
Although the program says it returns, fwrite doesnt print any data at the text file
and this is how I load the data to return it to the struct array but its not working
void loadDATA(){
FILE *fp;
char line[500];
fp=fopen("database.dbf","rb+");
if(fp == NULL){
fp = fopen("database.dbf", "wb");
}
while (fgets(line, sizeof(line), fp)){
last++;
fscanf(line,"%d %s %s %s %d %s %2.f", &array[last].pid, array[last].lname, array[last].fname,array[last].mname, &array[last].age, array[last].subject, &array[last].grade);
insert(array.tempID, array.L, array.F, array.M, array.TempAge, array.Sub, array.Tempgrade);
}
fclose(fp);
}
## MY STRUCT ##
typedef struct clientes{
int cod_cliente;
char name[100];
char country[100];
char city[100];
char email[100];
int nif;
char n_passporte[50];
char n_carta_conducao[50];
char telefone[50];
}CLIENTE;
typedef struct Elem{
VEICULO info_veiculo;
CLIENTE info_cliente;
ALUGADO info_alugado;
struct Elem *seguinte;
}ELEMENTO;
## FUNCTIONS ##
int saveBinaryCliente(ELEMENTO *iniLista){
ELEMENTO *aux = NULL;
FILE *fp = NULL;
int res=0;
fp = fopen("clientes.dat", "wb");
if(fp == NULL){
printf("Erro ao abrir o ficheiro clientes!\n");
return -1;
}
for(aux=iniLista; aux!=NULL; aux=aux->seguinte){
/*
printf("%i %s %s %s %i %s %s %s %s\n", aux->info_cliente.cod_cliente, aux->info_cliente.nome, aux->info_cliente.pais, aux->info_cliente.cidade, aux->info_cliente.nif, aux->info_cliente.n_passporte, aux->info_cliente.n_carta_conducao, aux->info_cliente.email, aux->info_cliente.telefone);
*/
Receives every parameter until this printf above
res = fwrite(aux, sizeof(CLIENTE), 1, fp);
}
fclose(fp);
printf("Saved %i register clientes!\n", res);
return 0;
}
int readDataCliente(ELEMENTO **iniLista){
CLIENTE aux;
int res=0;
FILE *fp = NULL;
fp = fopen("clientes.dat", "rb");
if(fp == NULL){
printf("Error reading file clientes!\n");
return -1;
}
while (!feof(fp)){
res = fread(&aux, sizeof(CLIENTE), 1, fp);
if (res){
inserirCliente(&(*iniLista), aux);
}
}
fclose(fp);
return 0;
}
## OUTPUT ##
LISTING BEFORE CLOSING WITH 1 CLIENT INSERTED
1 nuno portugal porto 23421342 ASDFA0942 ASDF-434 ssss#hotmail.com +351093856273
**AFTER CLOSING PROGRAM AND SAVE TO BINARY FILE**
*****************************************************
* MENU CLIENTES *
*****************************************************
* *
* 1 - INSERT NEW CLIENTE *
* 2 - CHANGE INFO CLIENTE *
* 3 - LIST CLIENTES *
*****************************************************
Choose your CHOICE: 3
0 0
0 0
strange fact...all seemed to work before. Dunno why doesnt work now and it also saves when I dont insert a client and reads it. I have been poking my head for a while so i decided to ask you guys for your help, thank you.
So, I have to print a linked list from a file input, which I've managed to get working:
#include <stdio.h>
#include <stdlib.h>
typedef struct Vehicle{
int option;
char make [30];
char model[30];
int car_manufacture_date;
float maximum_velocity;
float mass;
int seats;
struct Vehicle *next;//linked list node
} vehicle_t;
int main (){
FILE* fp;
fp = fopen("vehicles.crash.txt", "r");
vehicle_t* first_car = malloc(sizeof(vehicle_t));
if (first_car == NULL){
printf("Error. Failed to allocate memory to first_car\n");
exit(1);
}
vehicle_t* current_vehicle = malloc(sizeof(vehicle_t));
if (current_vehicle == NULL){
printf("Error. Failed to allocate memory to current_vehicle\n");
exit(1);
}
vehicle_t* new_vehicle = malloc(sizeof(vehicle_t));
if (new_vehicle == NULL){
printf("Error. Failed to allocate memory to new_vehicle\n");
exit(1);
}
printf("GOOD1\n");
current_vehicle = first_car;
new_vehicle = first_car;
printf("GOOD2\n");
//Loading vehicles from file to linked list
if (fp != NULL)
{
printf("GOOD3\n");
while (fscanf(fp,"%d %s %s %d %f %f %d", &new_vehicle->option, new_vehicle->make, new_vehicle->model, &new_vehicle->car_manufacture_date,
&new_vehicle->maximum_velocity, &new_vehicle->mass, &new_vehicle->seats) != EOF)
{
printf("GOOD4\n");
current_vehicle->next = new_vehicle;
current_vehicle = current_vehicle->next;
new_vehicle = malloc(sizeof(vehicle_t));
if (first_car == NULL){
printf("Error. Failed to allocate memory\n");
new_vehicle->next=NULL;
exit(1);
}
printf("GOOD5\n");
}
close(fp);
printf("Input completed\n");
}
else
printf("Error! couldn't find file\n");
current_vehicle = first_car;
while (current_vehicle != NULL)
{
printf("Option: %d\tMake: %s\tModel: %s\tManufactured: %d\tMax Velocity: %.2f\tMass: %.2f\tSeats: %d\n",
current_vehicle->option, current_vehicle->make, current_vehicle->model, current_vehicle->car_manufacture_date,
current_vehicle->maximum_velocity, current_vehicle->mass, current_vehicle->seats);
new_vehicle = current_vehicle->next;
current_vehicle = current_vehicle->next;
};
printf("Printing completed");
return 0;
}
Everything works fine right until the last file item is printed out, after which the program crashes. From what I've seen in other posts, the while loop matches them all.
The printed "GOOD" statements are just checkpoints
The text in the file is formatted as: 1 Toyota Camry 2010 200.0 1100.0 5
I think you forget to set the ->next field of the last list node to NULL. You just called malloc, so the value could be anything random, making your printing failed.
The main reason for the infinite loop was failing to set the final next to NULL [as others have mentioned].
But, I think this is easier to see with the code simplified as yours, although mostly correct, was more complicated than it needed to be.
Anyway, this compiles but I didn't test it [please pardon the gratuitous style cleanup]:
#include <stdio.h>
#include <stdlib.h>
typedef struct Vehicle {
int option;
char make[30];
char model[30];
int car_manufacture_date;
float maximum_velocity;
float mass;
int seats;
struct Vehicle *next; // linked list node
} vehicle_t;
int
main()
{
FILE *fp;
fp = fopen("vehicles.crash.txt", "r");
if (fp == NULL) {
printf("Error! couldn't find file\n");
exit(1);
}
vehicle_t *first_car = NULL;
vehicle_t *previous_vehicle = NULL;
// Loading vehicles from file to linked list
while (1) {
vehicle_t *new_vehicle = malloc(sizeof(vehicle_t));
if (new_vehicle == NULL) {
printf("Error. Failed to allocate memory to new_vehicle\n");
exit(1);
}
// NOTE: the lack of this [in your equivalent code] was the reason
// for the infinite loop
new_vehicle->next = NULL;
if (fscanf(fp, "%d %s %s %d %f %f %d",
&new_vehicle->option, new_vehicle->make, new_vehicle->model,
&new_vehicle->car_manufacture_date, &new_vehicle->maximum_velocity,
&new_vehicle->mass, &new_vehicle->seats) == EOF) {
free(new_vehicle);
break;
}
if (first_car == NULL)
first_car = new_vehicle;
else
previous_vehicle->next = new_vehicle;
previous_vehicle = new_vehicle;
}
fclose(fp);
vehicle_t *current_vehicle = first_car;
while (current_vehicle != NULL) {
printf("Option: %d\tMake: %s\tModel: %s\tManufactured: %d\tMax Velocity: %.2f\tMass: %.2f\tSeats: %d\n",
current_vehicle->option, current_vehicle->make,
current_vehicle->model, current_vehicle->car_manufacture_date,
current_vehicle->maximum_velocity, current_vehicle->mass,
current_vehicle->seats);
current_vehicle = current_vehicle->next;
};
printf("Printing completed");
return 0;
}