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.
Related
The program should print the username of the user who has uploaded at least three videos.
I think that the problem is with the last nested for, the first row that is printed is correct, but the others aren't.
These are the files:
Archivio.txt
Ciro Esposito cir0esp ciro.esposito#gmail.com
Gennaro Sorrentino gennSor gennaro.sorrentino#gmail.com
Pasquale Zemma pasZem pasquale.zemma#gmail.com
Video.txt
cir0esp ciro.esposito#gmail.com Io_al_mare 15 34
pasZem pasquale.zemma#gmail.com Festa_di_laurea 358 623
gennSor gennaro.sorrentino#gmail.com Io_allo_stadio 45 97
cir0esp ciro.esposito#gmail.com Io_in_montagna 446 814
gennSor gennaro.sorrentino#gmail.com Io_al_parco 66 124
cir0esp ciro.esposito#gmail.com Io_in_auto 10 23
The code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
struct DATI{ // STRUTTURA NON DINAMICA
char nome [N];
char cognome [N];
char username[N];
char email [N];
};
struct DATI dati [N];
struct PROFILO{ // STRUTTURA NON DINAMICA
char username [N];
char email [N];
char titolo_video [N];
int durata_video;
int dimensione_video;
};
struct PROFILO profilo [N];
struct UTENTI{ // LINKED LIST
char* account;
struct UTENTI *next;
};
typedef struct UTENTI utenti;
// PROTOTIPO FUNZIONI
void Lista_utenti(FILE *ptr_archivio);
void Info_video(FILE *ptr_dati, FILE *ptr_video);
// MAIN
int main (){
FILE *ptr_archivio; //LINKED LIST
FILE *ptr_video;
FILE *ptr_dati;
// PER LA LINKED LIST
ptr_archivio = fopen("Archivio.txt" , "r");
// CONFRONTO ARCHIVIO E VIDEO
ptr_video = fopen("Video.txt" , "r");
ptr_dati = fopen("Archivio.txt" , "r");
Lista_utenti(ptr_archivio);
Info_video(ptr_dati, ptr_video);
return 0;
}
// DEFINIZIONE FUNZIONI
void Lista_utenti(FILE *ptr_archivio){ // FUNZIONE PER LA LINKED LIST
char lista [N];
utenti *current, *head;
head = current = NULL;
if (ptr_archivio == NULL){
printf("Errore, file non trovato!");
}
else{
while(fgets(lista,sizeof(lista), ptr_archivio)){
utenti *node = malloc(sizeof(utenti));
node->account = strdup(lista);
node->next = NULL;
if(head == NULL){
current = head = node;
}
else {
current = current->next = node;
}
}
fclose(ptr_archivio);
}
printf("LINKED LIST UTENTI\n");
for(current = head; current ; current=current->next){
printf("%s->", current->account);
}
printf("NULL\n");
}
void Info_video(FILE *ptr_dati, FILE *ptr_video){ // FUNZIONE PER CONFRONTO FILE ARCHIVIO E VIDEO
int counter = 0;
int j = 0;
int i = 0;
int totale = 0;
char video [N];
char archivio[N];
if (ptr_dati == NULL){
printf("Errore, file non trovato!");
}
else {
while(fgets(archivio, N, ptr_dati)!= NULL){
sscanf(archivio, "%s %s %s %s", dati[i].nome, dati[i].cognome, dati[i].username, dati[i].email);
printf("\n\n");
printf("Nome: %s\n" , dati[i].nome);
printf("Cognome: %s\n" , dati[i].cognome);
printf("Username: %s\n" , dati[i].username);
printf("Email: %s\n" , dati[i].email);
printf("\n\n");
i++;
}
}
fclose(ptr_dati);
if (ptr_video == NULL){
printf("Errore, file non trovato!");
}
else {
while(fgets(video, N, ptr_video)!= NULL){
sscanf(video, "%s %s %s %d %d", profilo[i].username, profilo[i].email, profilo[i].titolo_video, &profilo[i].durata_video, &profilo[i].dimensione_video);
printf("\n\n");
printf("Username: %s\n" , profilo[i].username);
printf("Email: %s\n" , profilo[i].email);
printf("Titolo video: %s\n" , profilo[i].titolo_video);
printf("Durata video: %d secondi\n" , profilo[i].durata_video);
printf("Dimensione video: %d mb\n" , profilo[i].dimensione_video);
totale = totale + profilo[i].durata_video;
i++;
printf("\n\n");
}
fclose(ptr_video);
}
printf("La durata totale di tutti i video caricati e' di %d secondi\n" , totale);
for(i=0; i<N; i++){
for (j=0; j<N; j++){
if (strcmp(dati[i].username,profilo[j].username)== 0){
counter = counter+1;
if (counter == 3){
printf("\nIl seguente utente %s ha caricato almeno 3 video" , dati[i].username);
counter = 0;
}
}
}
}
}
This is wrong:
for(i=0; i<N; i++){
for (j=0; j<N; j++){
You don't have N valid elements in dati and profilo, that's just the maximum. You should save the value of the counter after you read the user and video information. I've added variables dati_count and profilo_count.
You also need to set i back to 0 before the loop that reads from ptr_video, so that you fill in the profilo array from the beginning.
And you should check whether sscanf() succeeds.
#Include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
struct DATI{ // STRUTTURA NON DINAMICA
char nome [N];
char cognome [N];
char username[N];
char email [N];
};
struct DATI dati [N];
int dati_count;
struct PROFILO{ // STRUTTURA NON DINAMICA
char username [N];
char email [N];
char titolo_video [N];
int durata_video;
int dimensione_video;
};
struct PROFILO profilo [N];
int profilo_count;
struct UTENTI{ // LINKED LIST
char* account;
struct UTENTI *next;
};
typedef struct UTENTI utenti;
// PROTOTIPO FUNZIONI
void Lista_utenti(FILE *ptr_archivio);
void Info_video(FILE *ptr_dati, FILE *ptr_video);
// MAIN
int main (){
FILE *ptr_archivio; //LINKED LIST
FILE *ptr_video;
FILE *ptr_dati;
// PER LA LINKED LIST
ptr_archivio = fopen("Archivio.txt" , "r");
// CONFRONTO ARCHIVIO E VIDEO
ptr_video = fopen("Video.txt" , "r");
ptr_dati = fopen("Archivio.txt" , "r");
Lista_utenti(ptr_archivio);
Info_video(ptr_dati, ptr_video);
return 0;
}
// DEFINIZIONE FUNZIONI
void Lista_utenti(FILE *ptr_archivio){ // FUNZIONE PER LA LINKED LIST
char lista [N];
utenti *current, *head;
head = current = NULL;
if (ptr_archivio == NULL){
printf("Errore, file non trovato!");
}
else{
while(fgets(lista,sizeof(lista), ptr_archivio)){
utenti *node = malloc(sizeof(utenti));
node->account = strdup(lista);
node->next = NULL;
if(head == NULL){
current = head = node;
}
else {
current = current->next = node;
}
}
fclose(ptr_archivio);
}
printf("LINKED LIST UTENTI\n");
for(current = head; current ; current=current->next){
printf("%s->", current->account);
}
printf("NULL\n");
}
void Info_video(FILE *ptr_dati, FILE *ptr_video){ // FUNZIONE PER CONFRONTO FILE ARCHIVIO E VIDEO
int counter = 0;
int j = 0;
int i = 0;
int totale = 0;
char video [N];
char archivio[N];
if (ptr_dati == NULL){
printf("Errore, file non trovato!");
}
else {
while(fgets(archivio, N, ptr_dati)!= NULL){
if (sscanf(archivio, "%s %s %s %s", dati[i].nome, dati[i].cognome, dati[i].username, dati[i].email) != 4) {
continue;
}
printf("\n\n");
printf("Nome: %s\n" , dati[i].nome);
printf("Cognome: %s\n" , dati[i].cognome);
printf("Username: %s\n" , dati[i].username);
printf("Email: %s\n" , dati[i].email);
printf("\n\n");
i++;
}
}
fclose(ptr_dati);
dati_count = i;
if (ptr_video == NULL){
printf("Errore, file non trovato!");
}
else {
i = 0;
while(fgets(video, N, ptr_video)!= NULL){
if (sscanf(video, "%s %s %s %d %d", profilo[i].username, profilo[i].email, profilo[i].titolo_video, &profilo[i].durata_video, &profilo[i].dimensione_video) != 5) {
continue;
}
printf("\n\n");
printf("Username: %s\n" , profilo[i].username);
printf("Email: %s\n" , profilo[i].email);
printf("Titolo video: %s\n" , profilo[i].titolo_video);
printf("Durata video: %d secondi\n" , profilo[i].durata_video);
printf("Dimensione video: %d mb\n" , profilo[i].dimensione_video);
totale = totale + profilo[i].durata_video;
i++;
printf("\n\n");
}
fclose(ptr_video);
profilo_count = i;
}
printf("La durata totale di tutti i video caricati e' di %d secondi\n" , totale);
for(i=0; i<dati_count; i++){
for (j=0; j<profilo_count; j++){
if (strcmp(dati[i].username,profilo[j].username)== 0){
counter = counter+1;
if (counter == 3){
printf("\nIl seguente utente %s ha caricato almeno 3 video" , dati[i].username);
counter = 0;
}
}
}
}
}
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).
This question already has answers here:
When using gets to get a file name in C, the file opens but when using fgets it does not
(3 answers)
Closed 7 years ago.
guy's well I have this code
#include <stdio.h>
typedef struct
{
int numero, notaF, notaE;
char nome[100];
} ALUNO;
void lerFicheiro(char path[], ALUNO alunos[], int *i);
void escreverFicheiro(char path[], ALUNO alunos[], int tamanho);
int main()
{
//Declarações
int i=0,t=0;
char path[999], wpath[999];
ALUNO alunos[999];
FILE *f;
//Introdução do nome do ficheiro para leitura e para escrita
printf("Introduza a localização do ficheiro para leitura: ");
fgets(path,999,stdin); //segmentation fault e o fopen dá null (apenas no read)
printf("Introduza a localização do ficheiro para escrita: ");
fgets(wpath,999,stdin);
//Leitura do ficheiro
lerFicheiro(path,alunos,&t);
//Escrita do ficheiro
escreverFicheiro(wpath, alunos, t);
return 0;
}
void lerFicheiro(char path[], ALUNO alunos[],int *i)
{
FILE *f = fopen("dados1.txt","r");
if(f!=NULL)
{
while(fscanf(f,"%d\n",&alunos[*i].numero)==1)
{
fgets(alunos[*i].nome,100,f);
fscanf(f,"%d\n",&alunos[*i].notaF);
fscanf(f,"%d\n",&alunos[*i].notaE);
*i=*i+1;
}
}
else
{
printf("Erro ao abrir o ficheiro\n");
}
fclose(f);
}
void escreverFicheiro(char path[], ALUNO alunos[], int tamanho)
{
FILE *f = fopen(path,"w+");
int i = 0, notaFinal = 0;
for(i=0;i<tamanho;i++)
{
if(alunos[i].notaF>alunos[i].notaE)
notaFinal = alunos[i].notaF;
else
notaFinal = alunos[i].notaE;
if(notaFinal>=10)
{
fprintf(f,"%d\n",alunos[i].numero);
fputs(alunos[i].nome,f);
fprintf(f,"%d\n",notaFinal);
}
}
fclose(f);
}
But on the lerFicheiro function, on the fopen if I replace the "dados1.txt" by path I will get the error "Erro ao abrir o ficheiro" in english "Unable to open file" and right after segmentation fault
I can't find the error anywere
You should strip the trailing newline from the file name
char *sptr = strchr(path, '\n');
if (sptr) *sptr = '\0';
Also move the fclose(f);, you are trying to close a file you did not open.
void lerFicheiro(char path[], ALUNO alunos[],int *i)
{
FILE *f = fopen("dados1.txt","r");
if(f!=NULL)
{
while(fscanf(f,"%d\n",&alunos[*i].numero)==1)
{
fgets(alunos[*i].nome,100,f);
fscanf(f,"%d\n",&alunos[*i].notaF);
fscanf(f,"%d\n",&alunos[*i].notaE);
*i=*i+1;
}
fclose(f);
}
else
{
printf("Erro ao abrir o ficheiro\n");
}
}
I need a way to store data from a file as well as save it on a file, it all needs to be done through a list using pointers, as the menu specifies it has to be able to delete and search for an specific person`s data within the list, my problem is, it reads the data from the file and stores it, but the show (on screen) function gets stuck on a loop showing me the data it read from the file for the last person's information(what would go on the last node before pointing to NULL), the same happens with the save (to file) function and the search (on list) and delete (from list) functions, which leads me to think it's somehow not pointing to NULL at the end of the list, I checked several times every function and their calls and couldn't find anything wrong but I'm barely a student and I really need help with this, thanks in advance (I'm sorry if I didn't format the code properly).
This is the library I made with the functions I needed:
#define EOL '\n'
struct fecha{
int dia,mes,año;
};
struct lista{
long cedula;
int genero;
char nombre[20];
char apellido[20];
char direccion[50];
fecha f;
lista *prox;
};
void asignar (int i,char lectura[50],lista **t){
switch (i)
{
case 1:
(*t)->cedula=atol(lectura);//atol convierte string a long
break;
case 2:
(*t)->genero=atoi(lectura);//atoi convierte string a int
break;
case 3:
strcpy((*t)->nombre,lectura);
break;
case 4:
strcpy((*t)->apellido,lectura);
break;
case 5:
strcpy((*t)->direccion,lectura);
break;
case 6:
(*t)->f.dia=atoi(lectura);
break;
case 7:
(*t)->f.mes=atoi(lectura);
break;
case 8:
(*t)->f.año=atoi(lectura);
break;
};
}
void insertaCab(lista **p, char path[100]){
lista *t = new lista;//crea el nodo
FILE *archivo;//apuntador para el archivo
int i=1;
char lectura[50];
archivo = fopen(path, "r");
if (archivo != NULL){//Si el archivo existe
while (!feof(archivo)){//Mientras no es final de archivo
while (i<=8){//lee 8 lineas y pasa al siguiente nodo de la lista
memset(lectura, 0, 50);
fgets(lectura,50,archivo);//Lee una linea
asignar(i,lectura,&t);>le pasa a asignar el contador,los datos y el apuntador de la lista
i++;
}i=1;
t->prox =(*p);//T->datos->||
(*p)=t;//P->datos->||
}fclose(archivo);
}
}
void muestra(lista *p){
lista *t = p;
while (t){
printf("Cedula: %i\n",t->cedula);
if (t->genero == 1) printf("Genero: Femenino\n");
else printf("Genero: Masculino\n");
printf("Nombre: %s\n",t->nombre);
printf("Apellido: %s\n",t->apellido);
printf("Direccion: %s\n",t->direccion);
printf("Fecha de nacimiento: %i/%i/%i\n\n",t->f.dia,t->f.mes,t->f.año);
t=t->prox;
}
printf("\n");
}
int buscarlista(lista *p,long x){
lista *t=p;
while (t!= NULL ){
if (t->cedula == x)
return 1;
t=t->prox;
}
return 0;
}
void eliminar(lista **p, long x){
lista *t=(*p),*aux;
if (t!= NULL)
if (t->cedula == x){
(*p)=t->prox;
delete t;
}
else{
while ((t->prox!= NULL) && (t->prox->cedula!=x))
t=t->prox;
if (t->prox!= NULL){
aux=t->prox;
t->prox=aux->prox;
delete aux;
}
}
}
void guardar(lista *p,char path[100]){
lista *t= new lista;
t=p;//apuntador auxiliar para recorrer la lista
FILE *archivo;//apuntador para el archivo
archivo = fopen(path,"a");//abre el archivo en modo append, si no existe lo crea
if(archivo !=NULL){//Si el archivo existe
while (t){
fprintf(archivo,"Cedula: %i\n",t->cedula);
if (t->genero == 1) fprintf(archivo,"Genero: Femenino\n");
else fprintf(archivo,"Genero: Masculino\n");
fprintf(archivo,"Nombre: %s\n",t->nombre);
fprintf(archivo,"Apellido: %s\n",t->apellido);
fprintf(archivo,"Direccion: %s\n",t->direccion);
fprintf(archivo,"Fecha de nacimiento: %i/%i/%i\n\n",t->f.dia,t->f.mes,t->f.año);
t=t->prox;
}
fclose(archivo);
}
}
And this is my main:
void main ( )
{
lista *p=NULL;
long x = 0;
int op;
char path[100];
op=-1;
while (op!=0){
printf ("1. Agregar\n");
printf ("2. Buscar\n");
printf ("3. Eliminar\n");
printf ("4. Mostrar\n");
printf ("5. Guardar\n");
printf ("0. Salir\n");
scanf ("%d", &op);
switch (op){
case 1: printf("Introduzca la direccion del archivo:");
memset(path,0,100);//Inicializa dir
scanf("%s",path);//Lee la direccion del archivo
insertaCab(&p,path);//Recibe el apuntador de la lista y la direccion del archivo
break;
case 2: printf("Indique el numero de cedula a buscar:");
scanf("%d",&x);
if (buscarlista(p,x) == 1)printf("El numero %i se encuentra en la lista\n",x);
else printf("No se encuentra en la lista\n");
break;
case 3: printf("Indique numero de cedula a eliminar:");
scanf("%d",&x);
eliminar(&p,x);
break;
case 4: muestra(p);
break;
case 5: printf("Introduzca la direccion en donde desea guardar la lista:");
memset(path,0,100);
scanf("%s",path);
guardar(p,path);
break;
};
}
}
You aren't detecting EOF properly. Try this:
void insertaCab(lista **p, char path[100]){
char lectura[50];
FILE *archivo; = fopen(path, "r");
if (archivo == NULL) return;
lista *t = new lista;
while (fgets(lectura, 50, archivo)) {
for (i = 1; i <= 8 && fgets(lectura, 50, archivo); i++)
asignar(i, lectura, &t);
if (i <= 8) break; // reached EOF before 8 lines were read.
t->prox = *p;
*p = t;
}
fclose(archivo);
}
Alright so I was able to solve it, I was missing the use of the malloc function, that's the reason as to why the list never got to NULL. The following is the fixed and working version of the function to input data into the list from the file:
void insertaCab(lista **p, char path[100]){
lista *t = new lista;
t = (struct lista *) malloc( sizeof(struct lista) );
char lectura[50];
int i=1;
FILE *archivo = fopen(path, "r");
if (archivo == NULL) return;
while (fgets(lectura,50,archivo)){
t = (struct lista *) malloc( sizeof(struct lista) );
for (i=1; (i<=8) && (fgets(lectura,50,archivo)); i++)
asignar(i,lectura,&t);
if(i<=8) break;
t->prox =(*p);
(*p)=t;
}
fclose(archivo);
}
i've a problem with read/write from file and view correctly the input:
// LOAD THE LIST FROM THE FILE
struct elemento *caricalista(struct elemento *p) {
struct elemento *punt;
FILE * utenti = fopen ("miarubrica.txt", "r");
char nome[MAX];
char cognome[MAX];
char telefono[MAX];
char mail[MAX];
if (utenti == NULL) {
printf("non ho caricato gli utenti");
} else {
while (!feof(utenti)) {
if (p != NULL) {
punt = (struct elemento *)malloc(sizeof(struct elemento));
fscanf(utenti, "%s", nome);
puts(nome);
fscanf(utenti, "%s", cognome);
puts(cognome);
fscanf(utenti, "%s", telefono);
puts(telefono);
fscanf(utenti, "%s", mail);
puts(mail);
strcpy(punt->nome, nome);
strcpy(punt->cognome, cognome);
strcpy(punt->telefono, telefono);
strcpy(punt->mail, mail);
punt->pun = p;
} else if (p == NULL) {
p = (struct elemento *)malloc(sizeof(struct elemento));
fscanf(utenti, "%s", nome);
fscanf(utenti, "%s", cognome);
fscanf(utenti, "%s", telefono);
fscanf(utenti, "%s", mail);
strcpy(p->nome, nome);
strcpy(p->cognome, cognome);
strcpy(p->telefono, telefono);
strcpy(p->mail, mail);
p->pun = NULL;
punt = p;
}
}
}
fflush(utenti);
fclose(utenti);
return(punt);
}
// SAVE THE LIST
int salva(struct elemento *p) {
FILE *stream = fopen("miarubrica.txt", "w");
while (p != NULL) {
// Scrive sul file
fprintf(stream, "%s ", p->nome);
fprintf(stream, "%s ", p->cognome);
fprintf(stream, "%s ", p->mail);
fprintf(stream, "%s \n", p->telefono);
p = p->pun;
}
fflush(stream);
fclose(stream);
return;
}
this write me (example)
pippo disney 02345432 pippodisney#pippodisney.com
in miarubrica.txt but when i read it with a method that read lists (it works), i see
pippo disney 02345432 pippodisney#pippodisney.com
pippo disney 02345432 pippodisney#pippodisney.com
two times in the shell. what's wrong?
Here's a quick fix. You've mixed the stuff with "->pun" pointer. I've removed the salva() method since you do not use it.
#include <stdio.h>
#include <malloc.h>
#define MAX (256)
struct elemento {
char nome[MAX], cognome[MAX], telefono[MAX], mail[MAX];
struct elemento* pun;
};
// LOAD THE LIST FROM THE FILE
struct elemento *caricalista(struct elemento *p) {
struct elemento *punt = p;
FILE * utenti = fopen ("miarubrica.txt","r");
if(!utenti) { printf("non ho caricato gli utenti"); return p; }
while(!feof(utenti)) {
punt= (struct elemento *)malloc(sizeof(struct elemento));
fscanf(utenti,"%s%s%s%s",
punt->nome, punt->cognome, punt->telefono, punt->mail);
printf("%s %s %s %s\n", /* print new element */
punt->nome, punt->cognome, punt->telefono, punt->mail);
punt->pun = p; /* old list at the end */
p = punt;
}
fclose(utenti);
return(punt);
}
int main() { caricalista(NULL); return 0; }
In caricalista there appears to be some confusion about whether you're prepending (putting the new entry before the one pointed to by p) or appending (put the new entry after the one pointed to by p).
For example, if p isn't NULL, it does punt->pun = p;, leaving p unchanged, but then on the next iteration it does the same.
Also, if the file is empty, it will return punt uninitialised.