my discord bot is not working properly why? - discord

I have created a Discord bot for my Minecraft server. The bot connects to my Discord server. The problem is that it does not respond. (See code).
#Override
public void onMessageReceived(MessageReceivedEvent event) {
if(event.getAuthor().isBot() || event.isWebhookMessage()) return;
TextChannel textChannel = event.getGuild().getTextChannelById("850164284402040872");
String[] args = event.getMessage().getContentRaw().split(" ");
if(args[0].equalsIgnoreCase("!link")) {
if(event.getChannel().equals(textChannel)) {
if (Objects.requireNonNull(event.getMember()).getRoles().stream().filter(role -> role.getId().equals("834086832408625152")).findAny().orElse(null) != null) {
textChannel.sendMessage(":x: **|** Error! " + event.getAuthor().getAsMention() + ", du bist bereits verifiziert!").queue();
return;
}
if (uuidIdMap.containsValue(event.getAuthor().getId())) {
textChannel.sendMessage(":x: **|** Error! " + event.getAuthor().getAsMention() + ", du hast bereits einen Code generiert!").queue();
return;
}
if (args.length != 2) {
textChannel.sendMessage(":x: **|** Error! Du musst einen Spieler angeben!").queue();
return;
}
Player target = Bukkit.getPlayer(args[1]);
if (target == null) {
textChannel.sendMessage(":x: **|** Error! Der Spieler konnte nicht gefunden werden").queue();
return;
}
int n = 20;
uuidCodeMap.put(target.getUniqueId(), randomCode(n));
uuidIdMap.put(target.getUniqueId(), event.getAuthor().getId());
for(String code : uuidCodeMap.values()) {
event.getAuthor().openPrivateChannel().complete().sendMessage("Hey! Du hast erfolgreich einen Code generiert!\n" + "Benutze diesen Befehl: ``/discord " + code + "``").queue();
}
textChannel.sendMessage(":white_check_mark: **|** Ein Code wurde generiert. Schaue bitte nach.").queue();
}
}
}

Related

JSONParser gives out everything twice

i was trying to make a JSONParser in C and it partly works.
The only problem is that the Terminal shows everything twice.
For Example, instead of showing just "Name", it gives out "Name" Name.
Thats the Code (some of the variables and comments are in German):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct person {
int PID;
int alter;
int freunde[20];
char* vname;
char* nname;
}person;
int MAX_PERSONS = 10;
char* substr(const char *source, int m, int n)
{
int len = abs(n - m);
char *destination = (char*)malloc(sizeof(char) * (len + 1));
for (int i = m; i < n && (*(source + i) != '\0'); i++)
{
*destination = *(source + i);
destination++;
}
*destination = '\0';
return destination - len;
}
const char* readNext(FILE* fp)
{
const char* string = malloc(1024); /*Speicherreservierung*/
const char* retvalue;
if (fscanf(fp, "%s", string) == 1) /*solange es erfolgreich ist, fragt es ab, bis ein leerzeichen kommt*/
{
while(strcmp(string,":") == 0 ) /*doppelpunkt wird ignoriert*/
{
fscanf(fp, "%s", string);
}
printf("\n %s", string); /*gibt einen String aus*/
if(strncmp(string,"\"",1) == 0)
{
if(strcmp(substr(string, strlen(string)-1, 1 ),",") == 0) /*kontrolliert, ob ein Beistrich vorkommt*/
{
retvalue = substr(string, 1, strlen(string)-2); /*kommt ein Beistrich vor, so werden zwei vom ende abgezogen, sonst nur einer*/
}
else
{
retvalue = substr(string, 1, strlen(string)-1);
} /*nun sind die Anfuehrungszeichen weg*/
printf("\n %s", retvalue);
return retvalue;
}
else
{
printf("\n %s", string);
return string;
}
}
return NULL;
}
int readInit(FILE* fp) /*hiermit wird der Anfang der Datei gelesen*/
{
const char* readValue= readNext(fp);
}
return strcmp(readValue,"{"); /*string wird mit { verglichen*/
void readPid(FILE* fp, person* pp)
{
const char* a = readNext(fp); /*file pointer auf die naechste stelle*/
if(strstr(a, "pid")> 0) /*kontrolle, ob wir schon an der Stelle PID sind*/
{
a = readNext(fp);
}
(*pp).PID = atoi(a); /*https://www.proggen.org/doku.php?id=c:lib:stdlib:atoi: die Funktion atoi wird in diesem Fall die anfuehrungszeichen los und speichert die ID ab*/
}
void readName(FILE* fp, person* pp)
{
readNext(fp); /*pointer wird weitergesetzt*/
if(readInit(fp) != 0) /*ueberpruefung ob es richtig startet*/
{
printf("\n Falsche Syntax - File does not start with {") ;
}
const char* a = readNext(fp); /*filepopinter geht weiter*/
if(strstr(a, "vname") > 0) /*Richtigkeits ueberpruefung*/
{
(*pp).vname = readNext(fp); /*pointer geht weiter auf namen und speichert es ins struct*/
}
a = readNext(fp);
if(strstr(a, "nname") > 0) /*ueberpruefung ob es der nachname ist*/
{
(*pp).nname = readNext(fp); /*file pointer geht auf nachnamen und speichert*/
}
}
int readAge(FILE* fp,person* pp )
{
readNext; /*ueberspringen des },*/
const char* a = readNext(fp);
if(strstr(a, "alter")> 0) /*ueberpruefung ob wir an der stelle alter sind*/
{
a = readNext(fp); /*filepointer geht weiter zum alter*/
}
(*pp).PID = atoi(a);
return 0;
}
int readFreunde(FILE* fp,person* pp )
{
readNext; /*ueberspringen des ,*/
const char* a = readNext(fp);
if(strstr(a, "freunde")> 0) /*ueberpruefung ob wir an der stelle freunde sind*/
{
a = readNext(fp); /*filepointer geht weiter zu den freunden ids*/
}
(*pp).PID = atoi(a);
return 0;}
/*
int * readFriends(FILE* fp)
{
int retvalue[] = {0,1};
return retvalue;
}
*/
person* readPerson(FILE* myFileRef) /*file pointer wird as parameter mitgegeben*/
{
person* myPers = (person*) malloc(1 * sizeof(person)); /*speicher wird reserviert fuer die auszulesenden daten der person*/
if(readInit(myFileRef) != 0) /*es wird ueberprueft ob das file richtig beginnt*/
{
printf("\n Falsche Syntax - File does not start with {") ;
}
readPid(myFileRef, myPers); /*auslagerung der einzelnen daten in funktionen*/
readName(myFileRef, myPers);
readAge(myFileRef, myPers);
readFreunde(myFileRef, myPers);
return myPers;
}
void optionone()
{
FILE* myJson = NULL; /*Initialisierung des File Pointers*/
printf("Option 1 gewaehlt \n");
myJson = fopen("personen.json", "r"); /*file wird mit "r" geoeffnet, das heißt die Datei wird nur gelesen und nicht geaendert*/
person* myPersLib[MAX_PERSONS] ; /*struct wird initialisiert*/
int i = 0;
if(myJson != NULL) /*ueberpruefung ob das file leer ist*/
{
person* myPers = readPerson(myJson); /*ablesefunktion ausgelagert*/
while(&myPers != NULL && i < MAX_PERSONS) /*schleife um alle strings durchzugehen, insofern das file nicht leer ist und man die maximale anzahl nicht ueberschreitet*/
{
myPersLib[i] = myPers;
i++;
myPers = readPerson(myJson);
}
fclose(myJson); /*datei wird geschlossen*/
}
else
{
printf("Datei nicht vorhanden"); /*ist die Datei nicht in dem gleichen Ordner, so entsteht eine Fehlermeldung "Datei nicht vorhanden" */
}
}
void optiontwo()
{
char str[15];
int b = 0;
person mypers;
printf("\n Option 2 gewaehlt\n");
printf("\nID eingeben: "); /*Abfrage der ID*/
scanf("%d", &b);
b = mypers.PID;
printf("\nVorname eingeben:"); /*Abfrage des Vornamens*/
scanf("%s", str);
*str = mypers.vname; /*string pointer weil es eine "modifiable value" sein muss*/
printf("\n Nachname eingeben:"); /*Abfrage des Nachnamens*/
scanf("%s", str);
*str = mypers.nname;
printf("\n Alter eingeben: "); /*Abfrage des Alters*/
scanf("%d", &b);
b = mypers.alter;
printf("\n ID eingeben: "); /*Abfrage der ID (friends)*/
scanf("%d", &b);
b = mypers.freunde;
}
int main()
{
int a = 0;
printf("1. Einlesen \t 2. Eingeben und als File speichern");
printf("\n Option waehlen: "); /*mit der switch case wird die Option abgefragt, einlesen oder eingeben*/
scanf("%d", &a);
switch (a)
{
case 1: /*erste option der switch case*/
optionone();
break;
case 2: /*zweite option der switch case*/
optiontwo();
break;
default:
printf("Ungueltige Option"); /*wird etwas anderes als 1 oder zwei bei der Optionsauswahl ausgewaehlt, so wird es unterbrochen und es entsteht eine Fehlermeldung*/
break;
}
return 0;
}
And after the terminal compiles the File, thats what it spits out:
1. Einlesen 2. Eingeben und als File speichern
Option waehlen: 1
Option 1 gewaehlt
{
{
"pid"
pid
"1138",
1138"
"name"
name
{
{
"vname"
vname
"Leia",
Leia"
"nname"
nname
"Organa"
Organa
},
},
"alter"
alter
"21",
21"
Falsche Syntax - File does not start with {
"freunde"
freunde
[
[
{"pid"
{"pid"
Falsche Syntax - File does not start with {
"0987"}
0987"
,
,
{"pid"
{"pid"
"7778"}
7778"
]
]
Falsche Syntax - File does not start with {
},
},
{
{
"pid"
pid
Falsche Syntax - File does not start with {
"7778",
7778"
"name"
name
{
{
"vname"
vname
"Luke",
Luke"
Falsche Syntax - File does not start with {
"nname"
nname
"Skywalker"
Skywalker
},
},
Falsche Syntax - File does not start with {
"alter"
alter
"21",
21"
"freunde"
freunde
[
[
{"pid"
{"pid"
Falsche Syntax - File does not start with {
"0987"}
0987"
,
,
{"pid"
{"pid"
Falsche Syntax - File does not start with {
"1138"}
1138"
]
]
},
},
{
{
"pid"
pid
Falsche Syntax - File does not start with {
"0987",
0987"
"name"
name
{
{
"vname"
vname
"Din",
Din"
"nname"
nname
"Djarin"
Djarin
},
},
"alter"
alter
"35",
35"
Falsche Syntax - File does not start with {
"freunde"
freunde
[
[
{"pid"
{"pid"
Falsche Syntax - File does not start with {
"7778"}
7778"
,
,
{"pid"
{"pid"
"1138"}
1138"
]
]
Falsche Syntax - File does not start with {
}
}

Primefaces file download handling errors

Basically my problem is: How do I display an error message on my page and cancel a download, when the generation of the file to download has failed.
Primefaces 7. I would be willing to update to 11 (which breaks some of my code ..) if I would see a method which achieves this in 11
<p:commandButton id="downloadButtonAllCSV" widgetVar="downloadButtonAllCSV" value="Download alle CSV" onclick="PrimeFaces.monitorDownload(start, stop)" icon="ui-icon-arrowthick-1-s" styleClass="button" update="#form">
<p:fileDownload value="#{reportingController.CSVAllGCG}" />
</p:commandButton>
<p:growl></p:growl>
<p:dialog widgetVar="csvError" header="Fehler bei CSV Erzeugung">
<h:outputText value="Fehler bei CSV Erzeugung"></h:outputText>
</p:dialog>
My bean code basically checks if the number of selected samples is smaller than some cofigured value to avoid an OutOfMemory. My problem is that the attempts to show some error on the web page in the else block do not work. Neither the growl, nor the dialog show up.
public StreamedContent getCSVAllGCG() {
InputStream targetStream = null;
String csv = "";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(GCGNachrichtDTO.REP_CSV_HEADER);
if (getAnzahl().intValue() < this.maxDownloads) {
List<GCGNachrichtDTO> allDtos = this.reportMessageDAO.findGCGNachichten(0, getAnzahl().intValue(), filter, true);
String dtoString = allDtos.stream().map(d -> d.getMonCSVString()).collect(Collectors.joining());
stringBuilder.append(dtoString);
csv = stringBuilder.toString();
targetStream = new ByteArrayInputStream(csv.getBytes());
} else {
String message = "Mehr als " + maxDownloads + " Eintraege koennen nicht verarbeitet werden";
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, message, message);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
message += " Konfiguration mit gcg.monitoring.max.downloads. Ein zu hoher Wert kann zu einer OutOfMemoryError fuehren.";
log.info(message);
PrimeFaces.current().executeScript("PF('csvError').show()");
targetStream = new ByteArrayInputStream(message.getBytes());
}
return new DefaultStreamedContent(targetStream, "text/csv", "reporting.csv");
}
#adam:
<p:commandButton id="downloadButtonAllCSV" widgetVar="downloadButtonAllCSV" value="Download alle CSV" icon="ui-icon-arrowthick-1-s" styleClass="button" update="#form" actionListener="#{reportingController.actionCSVAllGCG()}">
<p:fileDownload value="#{reportingController.stream}" />
</p:commandButton>
public void actionCSVAllGCG() {
InputStream targetStream = null;
String csv = "";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(GCGNachrichtDTO.REP_CSV_HEADER);
if (getAnzahl().intValue() <= this.maxDownloads) {
List<GCGNachrichtDTO> allDtos = this.reportMessageDAO.findGCGNachichten(0, getAnzahl().intValue(), filter, true);
String dtoString = allDtos.stream().map(d -> d.getMonCSVString()).collect(Collectors.joining());
stringBuilder.append(dtoString);
csv = stringBuilder.toString();
targetStream = new ByteArrayInputStream(csv.getBytes());
} else {
String message = "Mehr als " + maxDownloads + " Eintraege koennen nicht verarbeitet werden";
log.info(message);
targetStream = new ByteArrayInputStream(message.getBytes());
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, message, message);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
message += " Konfiguration mit gcg.monitoring.max.downloads. Ein zu hoher Wert kann zu einer OutOfMemoryError fuehren.";
log.info("------- ******** " + message);
PrimeFaces.current().executeScript("PF('csvError').show()");
}
this.stream = new DefaultStreamedContent(targetStream, "text/csv", "reporting.csv");
}
This does not work either, nothing happens...

Memory Corruption in malloc

I am having problems with allocation. When I try to allocate my struct variables, it gives me the error of malloc corruption. And I am kind of new at C so, I think I need some help.
More precisely when I try to allocate in this line:
g->nos = (no_grafo **)malloc(sizeof(no_grafo*))
it gives me the error I am talking about.
There is my line error in the compiler, struct, my code, and my call code:
Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig#entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
51 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) backtrace
#0 __GI_raise (sig=sig#entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
#1 0x00007fffff040801 in __GI_abort () at abort.c:79
#2 0x00007fffff089897 in __libc_message (action=action#entry=do_abort, fmt=fmt#entry=0x7fffff1b6b9a "%s\n")
at ../sysdeps/posix/libc_fatal.c:181
#3 0x00007fffff09090a in malloc_printerr (str=str#entry=0x7fffff1b4e0e "malloc(): memory corruption") at malloc.c:5350
#4 0x00007fffff094994 in _int_malloc (av=av#entry=0x7fffff3ebc40 <main_arena>, bytes=bytes#entry=8) at malloc.c:3738
#5 0x00007fffff0970fc in __GI___libc_malloc (bytes=8) at malloc.c:3057
#6 0x0000000000402a2c in grafo_novo ()
#7 0x0000000000402f59 in criaGrafo ()
#8 0x0000000000400ca0 in verifica_criaGrafo ()
#9 0x0000000000401a9b in main ()
struct no_grafos;
typedef struct
{
int peso_ligacao;
struct no_grafos *destino;
} ligacao;
typedef struct no_grafos
{
char *nome_user;
int tamanho;
ligacao **ligacoes;
} no_grafo;
typedef struct
{
int tamanho; /* numero de nos */
no_grafo **nos; /* vetor de nos */
} grafo;
grafo* grafo_novo()
{
grafo* g;
g = (grafo*)malloc(sizeof(grafo));
if(g == NULL){
return NULL;
}
g->nos = (no_grafo **)malloc(sizeof(no_grafo*));
if(g->nos == NULL){
return NULL;
}
g->nos = NULL;
g->tamanho = 0;
return g;
}
void grafo_apaga(grafo* g)
{
if(g == NULL)
return;
if(g->nos != NULL){
int i,j;
for (i =0; i< g->tamanho; g++){
for(j=0; j< g->nos[i]->tamanho;j++){
free(g->nos[i]->ligacoes[j]);
}
free(g->nos[i]);
}
free(g->nos);
free(g);
g = NULL;
}
return;
}
no_grafo * no_insere(grafo *g, char *user)
{
if(g == NULL || user == NULL) return NULL;
for (int i = 0; i < g->tamanho; i++){
if (strcmp(g->nos[i]->nome_user, user) == 0) return NULL;
}
no_grafo * no = (no_grafo*)malloc(sizeof(no_grafo));
if(no == NULL){
return NULL;
}
no->nome_user = (char*)calloc(strlen(user)+1,sizeof(char));
if(no->nome_user == NULL){
free(no);
no = NULL;
return NULL;
}
else{
strcpy(no->nome_user,user);
}
no->ligacoes = (ligacao**)malloc(sizeof(ligacao*));
if(no->ligacoes == NULL){
free(no->nome_user);
free(no);
no = NULL;
return NULL;
}
g->nos = (no_grafo **)realloc(g->nos, (g->tamanho + 1) * sizeof(no_grafo *));
if(g->nos == NULL){
return NULL;
}
no->tamanho = 0;
g->nos[g->tamanho] = no;
g->tamanho++;
return no;
}
int cria_ligacao(no_grafo *origem, no_grafo *destino, int peso)
{
if(origem == NULL || destino == NULL || peso < 1) return -1;
for(int i=0; i < origem->tamanho; i++){
if(origem->ligacoes[i]->destino==destino){ // ligacao já existente
return 0;
}
}
ligacao *liga = (ligacao*)malloc(sizeof(ligacao));
if(liga == NULL){
return -1;
}
liga->destino = destino;
liga->peso_ligacao = peso;
origem->ligacoes[origem->tamanho] = liga;
origem->tamanho++;
return 0;
}
no_grafo * encontra_no(grafo *g, char *nomeU)
{
if(g == NULL) return NULL;
for(int i=0; i< g->tamanho; i++){
if(strcmp(g->nos[i]->nome_user,nomeU)==0){
return g->nos[i];
}
}
return NULL;
}
grafo * criaGrafo(tabela_dispersao *td)
{
if(td == NULL){
return NULL;
}
grafo * g;
g = grafo_novo();
int n[2] = {0}, contador = 0;
while(td->elementos[contador] != NULL){
no_grafo *no_remetente = no_insere(g,td->elementos[contador]->msg->remetente);
if(no_remetente != NULL){
mensagem ** tabela = tabela_listagem(td,td->elementos[contador]->msg->remetente);
if(tabela != NULL){
while(tabela[contador] != NULL){
no_grafo *no_destinatario = no_insere(g,tabela[contador]->destinatario);
if(no_destinatario != NULL){
ligacao2(td,tabela[contador]->remetente,tabela[contador]->destinatario,n);
if(n[0] != 0 && n[0] != -1){
cria_ligacao(no_remetente,no_destinatario,n[0]);
}
}
contador++;
}
}
}
td->elementos[contador] = td->elementos[contador]->proximo;
}
return g;
}
no_grafo **lista_amigos(grafo *g, char *nomeU, int *n)
{
if(g== NULL || nomeU == NULL){
return NULL;
}
n = (int*)malloc(sizeof(int));
if(n == NULL)
return NULL;
no_grafo **lista = (no_grafo**)calloc(g->tamanho,sizeof(no_grafo*));
if(lista == NULL) return NULL;
int contador=0;
for(int i = 0; i < g->tamanho;i++){
if(strcmp(g->nos[i]->nome_user,nomeU) == 0){
for(int j = 0; j < g->nos[i]->tamanho; j++){
if(g->nos[i]->ligacoes[j]->peso_ligacao > 3){
// potencial amigo
for(int t = 0; t < g->nos[i]->ligacoes[j]->destino->tamanho; t++){
if((g->nos[i]->ligacoes[j]->destino->ligacoes[t]->peso_ligacao > 3) && (g->nos[i]->ligacoes[j]->destino->ligacoes[t]->destino == g->nos[i])){
lista[contador] = g->nos[i]->ligacoes[j]->destino;
n[0]++;
contador++;
}
}
}
}
}
}
lista = (no_grafo**)realloc(lista,contador*sizeof(no_grafo*));
return lista;
}
no_grafo ** identifica_ciclo(grafo *g, char *nomeU, int M, int *n)
{
if(g== NULL || nomeU == NULL)
return NULL;
return NULL;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "tabdispersao.h"
#include "grafo.h"
#include "stnova.h"
/* DEFINES E VARIAVEIS GLOBAIS UTEIS PARA OS TESTES */
#define MAX_LINHA 1024
#define TAB_MSG 17
#define TAB_MSG1 997
/* VERIFICACOES IMPLEMENTADAS */
int verifica_tabela_existe(tabela_dispersao* td)
{
int er=0;
int t=tabela_existe(td, "FERNANDO");
if(t!=0)
{
printf("...verifica_tabela_existe(Remetente inexistente): tabela_existe deu diferente de 0 (ERRO)\n");
er++;
}
else
printf("...verifica_tabela_existe(Remetente inexistente): tabela_existe deu 0 (OK)\n");
t=tabela_existe(td, "ANA");
if(t!=7)
{
printf("...verifica_tabela_existe(Remetente que existe): tabela_existe deu diferente de 7 (ERRO)\n");
er++;
}
else
printf("...verifica_tabela_existe(Remetente que existe): tabela_existe deu 7 (OK)\n");
return er;
}
int verifica_tabela_listagem(tabela_dispersao* td)
{
int er=0;
mensagem** t=tabela_listagem(td, "FERNANDO");
if(t==NULL)
{
printf("...verifica_tabela_listagem(Remetente inexistente): tabela_listagem deu NULL (ERRO)\n");
er++;
} else
{
if(t[0]!=NULL)
{
printf("...verifica_tabela_listagem(Remetente inexistente): tabela_listagem a primeira posição deu diferente de NULL (ERRO)\n");
er++;
}
else
printf("...verifica_tabela_listagem(Remetente inexistente): tabela_listagem a primeira posição deu NULL (OK)\n");
}
free(t);
t=tabela_listagem(td, "ANA");
if(t==NULL)
{
printf("...verifica_tabela_listagem(Remetente inexistente): tabela_listagem deu NULL (ERRO)\n");
er++;
}
else {
int i=0;
if (t)
{
while (t[i]!=NULL)
{
i++;
}
if(i!=7)
{
printf("...verifica_tabela_listagem(Remetente que existe): tabela_listagem deu diferente de 7 mensagens(ERRO)\n");
er++;
}
else
printf("...verifica_tabela_listagem(Remetente que existe): tabela_listagem deu 7 mensagens(OK)\n");
i=0;
free(t);
}
}
return er;
}
int verifica_ligacao2(tabela_dispersao* td)
{
int er=0;
int totMsg[2]={0};
ligacao2(td,"LUIS","FERNANDO",totMsg);
if(totMsg[0]!=-1 || totMsg[1]!=-1)
{
printf("...verifica_ligacao2(Os remetentes sao inexistente): ligacao2 deu diferente de -1 -1 (ERRO)\n");
er++;
}
else
printf("...verifica_ligacao2(Os remetentes sao inexistente): ligacao2 deu -1 -1 (OK)\n");
ligacao2(td,"PEDRO","MARIA",totMsg);
if(totMsg[0]!=0 || totMsg[1]!=1)
{
printf("...verifica_ligacao2(Remetentes existentes): ligacao2 deu diferente de 0 1 (ERRO)\n");
er++;
}
else
printf("...verifica_ligacao2(Remetentes existentes): ligacao2 deu 0 1 (OK)\n");
return er;
}
int verifica_criaGrafo(tabela_dispersao* td,grafo **g)
{
int er=0;
*g=criaGrafo(td);
if (*g)
{
if((*g)->tamanho!=7)
{
printf("...verifica_criaGrafo(numero de nos): criaGrafo deu diferente de 7 (ERRO)\n");
er++;
}
else
printf("...verifica_criaGrafo(numero de nos): criaGrafo deu 7 (OK)\n");
} else
{
printf("...verifica_criaGrafo(numero de nos): criaGrafo deu NULL (ERRO)\n");
er++;
}
return er;
}
int verifica_lista_amigos(grafo *g)
{
int er=0;
int n=0;
no_grafo **nos=lista_amigos(g, "PEDRO", &n);
if(n!=0)
{
printf("...verifica_lista_amigos(sem amigos): lista_amigos deu diferente de 0(ERRO)\n");
er++;
}
else
printf("...verifica_lista_amigos(sem amigos): lista_amigos deu 0 (OK)\n");
free(nos);
nos=lista_amigos(g, "ANA", &n);
if(n==0)
{
printf("...verifica_lista_amigos(sem amigos): lista_amigos deu 0 (ERRO)\n");
er++;
}
else
if (strcmp(nos[0]->nome_user,"MAFALDA"))
{
printf("...verifica_lista_amigos(com amigos): lista_amigos deu diferente da amiga MAFALDA (ERRO)\n");
er++;
}
else
printf("...verifica_lista_amigos(com amigos): lista_amigos deu a amiga MAFALDA (OK)\n");
free(nos);
return er;
}
int verifica_identifica_ciclo(grafo *g)
{
int er=0;
no_grafo **nosciclo;
int r;
nosciclo=identifica_ciclo(g, "MARIA", 4, &r);
if(nosciclo==NULL)
{
printf("...verifica_identifica_ciclo(com ciclo): identifica_ciclo deu NULL (ERRO)\n");
er++;
}
else if(r!=4)
{
printf("...verifica_identifica_ciclo(com ciclo): identifica_ciclo deu um numero de nos diferente de 4 (ERRO)\n");
er++;
}
else
{
printf("...verifica_identifica_ciclo(com ciclo): identifica_ciclo deu um numero de nos igual a 4 (OK)\n");
printf("Os no´s foram: ");
for (int i=0;i<r-1;i++)
printf("[%d %s] : ",i+1,nosciclo[i]->nome_user);
printf("[%d %s]\n",r,nosciclo[r-1]->nome_user);
}
free(nosciclo);
return er;
}
int verifica_st_remove(estrutura *st)
{
int er=0;
elemento *el=st_remove(st,"ANA");
elemento *aux;
if(el==NULL)
{
printf("...verifica_st_remove(): st_remove deu NULL (ERRO)\n");
er++;
}
else
{ char amigo[TAMANHO_CHAVE];
int i=0;
if (strcmp(el->msg->remetente,"ANA")==0)
strcpy(amigo,el->msg->destinatario);
while (el)
{
i++;
aux=el->proximo;
if (el->msg->texto)
free(el->msg->texto);
free(el->msg);
free(el);
el=aux;
}
if((i==4) && (strcmp(amigo,"MAFALDA")==0))
{
printf("...verifica_st_remove(): st_remove removeu a amiga MAFALDA com 4 mensagens (OK)\n");
}
else
{
printf("...verifica_st_remove(): st_remove não removeu a amiga MAFALDA com 4 mensagens (ERRO)\n");
er++;
}
}
return er;
}
/*================================================= */
int verifica_tabela_existe1(tabela_dispersao* td)
{
int er=0;
int t=tabela_existe(td, "JACK");
if(t!=778)
{
printf("...verifica_tabela_existe(Remetente que existe): tabela_existe deu diferente de 778 (ERRO)\n");
er++;
}
else
printf("...verifica_tabela_existe(Remetente que existe): tabela_existe deu 778 (OK)\n");
return er;
}
int verifica_tabela_listagem1(tabela_dispersao* td)
{
int er=0;
mensagem** t=tabela_listagem(td, "JAKE");
if(t==NULL)
{
printf("...verifica_tabela_listagem(Remetente inexistente): tabela_listagem deu NULL (ERRO)\n");
er++;
}
else {
int i=0;
if (t)
{
while (t[i]!=NULL)
{
i++;
}
if(i!=521)
{
printf("...verifica_tabela_listagem(Remetente que existe): tabela_listagem deu diferente de 521 mensagens(ERRO)\n");
er++;
}
else
printf("...verifica_tabela_listagem(Remetente que existe): tabela_listagem deu 521 mensagens(OK)\n");
free(t);
}
}
return er;
}
int verifica_ligacao21(tabela_dispersao* td)
{
int er=0;
int totMsg[2]={0};
ligacao2(td,"CATES","HAMMOND",totMsg);
if(totMsg[0]!=135 || totMsg[1]!=109)
{
printf("...verifica_ligacao2(Remetentes existentes): ligacao2 deu diferente de 135 e 109 (ERRO)\n");
er++;
}
else
printf("...verifica_ligacao2(Remetentes existentes): ligacao2 deu 135 109 (OK)\n");
return er;
}
int verifica_criaGrafo1(tabela_dispersao* td,grafo **g)
{
int er=0;
*g=criaGrafo(td);
if (*g)
{
if((*g)->tamanho!=1545)
{
printf("...verifica_criaGrafo(numero de nos): criaGrafo deu diferente de 1545 nós (ERRO)\n");
er++;
}
else
printf("...verifica_criaGrafo(numero de nos): criaGrafo deu 1545 nós (OK)\n");
} else
{
printf("...verifica_criaGrafo(numero de nos): criaGrafo deu NULL (ERRO)\n");
er++;
}
return er;
}
int verifica_lista_amigos1(grafo *g)
{
int er=0;
int n=0,j,i,correto=0,resultado=0;
no_grafo **nos=lista_amigos(g, "WOMAN", &n);
char nomes[6][14]={"CHESS PLAYER","JACK","JACOB","JOE","MILES","ROB"};
if(n==0)
{
er++;
}
else
{
resultado=1;
for (i=0;i<n;i++)
{
correto=0;
for(j=0;j<6;j++)
{
if (strcmp(nos[i]->nome_user,nomes[j])==0)
{
correto=1;
break;
}
}
if (correto==0)
{
resultado=0;
}
}
if (!resultado)
{
printf("...verifica_lista_amigos(com amigos): lista_amigos deu pelos menos um diferente ""CHESS PLAYER"",""JACK"",""JACOB"",""JOE"",""MILES"",""ROB"" (ERRO)\n");
er++;
}
else
printf("...verifica_lista_amigos(com amigos): lista_amigos deu ""CHESS PLAYER"",""JACK"",""JACOB"",""JOE"",""MILES"",""ROB"" (OK)\n");
}
free(nos);
return er;
}
int verifica_identifica_ciclo1(grafo *g)
{
int er=0;
no_grafo **nosciclo;
int r;
nosciclo=identifica_ciclo(g, "ERNEST",8, &r);
if(nosciclo==NULL)
{
printf("...verifica_identifica_ciclo(com ciclo): identifica_ciclo deu NULL (ERRO)\n");
er++;
}
else if(r>=3 && r<=8)
{
printf("...verifica_identifica_ciclo(com ciclo): identifica_ciclo deu um numero de nos está entre 3 e 8 (OK)\n");
printf("Os no´s foram: ");
for (int i=0;i<r-1;i++)
printf("[%d %s] : ",i+1,nosciclo[i]->nome_user);
printf("[%d %s]\n",r,nosciclo[r-1]->nome_user);
}
else
{
printf("...verifica_identifica_ciclo(com ciclo): identifica_ciclo deu um numero de nos que não está entre 3 e 8 (ERRO)\n");
printf("Os no´s foram: ");
for (int i=0;i<r-1;i++)
printf("[%d %s] : ",i+1,nosciclo[i]->nome_user);
printf("[%d %s]\n",r,nosciclo[r-1]->nome_user);
er++;
}
free(nosciclo);
return er;
}
int verifica_st_remove1(estrutura *st)
{
int er=0;
clock_t start_t, end_t;
start_t = clock();
elemento *el=st_remove(st,"HELEN");
end_t = clock();
elemento *aux;
if(el==NULL)
{
printf("...verifica_st_remove(): st_remove deu NULL (ERRO)\n");
er++;
}
else
{ char amigo[TAMANHO_CHAVE];
int i=0;
if (strcmp(el->msg->remetente,"HELEN")==0)
strcpy(amigo,el->msg->destinatario);
while (el)
{
i++;
aux=el->proximo;
if (el->msg->texto)
free(el->msg->texto);
free(el->msg);
free(el);
el=aux;
}
if((i==67) && (strcmp(amigo,"CALVIN")==0))
{
printf("...verifica_st_remove(): st_remove removeu a amiga CALVIN com 67 mensagens (OK)\n");
printf("\tTempo a remover: %.8f\n", (double)(end_t - start_t) / CLOCKS_PER_SEC);
}
else
{
printf("...verifica_st_remove(): st_remove removeu a amiga %s com %d mensagens devia ser (CALVIN,67) (ERRO)\n",amigo,i);
er++;
}
}
return er;
}
/*================================================= */
int main()
{
int errCount=0, err;
char *fi= "dados.txt";
tabela_dispersao* td;
grafo *g;
td=tabela_carrega(fi,TAB_MSG);
printf("INICIO DOS TESTES: Boa sorte\n\n");
printf("Teste com poucos utilizadores\n\n");
err = verifica_tabela_existe( td);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_tabela_existe\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_tabela_existe passou\n\n");
}
err = verifica_tabela_listagem( td);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_tabela_listagem\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_tabela_listagem passou\n\n");
}
err = verifica_ligacao2( td);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_ligacao2\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_ligacao2 passou\n\n");
}
err = verifica_criaGrafo(td,&g);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_criaGrafo\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_criaGrafo passou\n\n");
}
err = verifica_lista_amigos(g);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_lista_amigos\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_lista_amigos passou\n\n");
}
err = verifica_identifica_ciclo(g);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_identifica_ciclo\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_identifica_ciclo passou\n\n");
}
estrutura *st=st_nova();
st_importa_tabela(st,td);
err = verifica_st_remove(st);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_st_remove\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_st_remove passou\n\n");
}
st_apaga(st);
tabela_apaga(td);
grafo_apaga(g);
/*================================================= */
/* Com um ficheiro maior */
char *fic= "dataset_partA.txt";
printf("Teste com muitos utilizadores\n\n");
td=tabela_carrega(fic,TAB_MSG1);
err = verifica_tabela_existe1(td);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_st_remove\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_st_remove passou\n\n");
}
err = verifica_tabela_listagem1( td);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_tabela_listagem\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_tabela_listagem passou\n\n");
}
err = verifica_ligacao21( td);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_ligacao2\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_ligacao2 passou\n\n");
}
err = verifica_criaGrafo1(td,&g);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_criaGrafo\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_criaGrafo passou\n\n");
}
err = verifica_lista_amigos1(g);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_lista_amigos\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_lista_amigos passou\n\n");
}
err = verifica_identifica_ciclo1(g);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_identifica_ciclo\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_identifica_ciclo passou\n\n");
}
st=st_nova();
st_importa_tabela(st,td);
err = verifica_st_remove1(st);
if(err)
{
printf("ERRO: %d erros encontrados em verifica_st_remove\n\n", err);
errCount += err;
}
else
{
printf("OK: verifica_st_remove passou\n\n");
}
st_apaga(st);
tabela_apaga(td);
grafo_apaga(g);
if (errCount == 0)
printf("FIM DOS TESTES: Todos os testes passaram\n");
else
printf("FIM DOS TESTES: Foram encontrados %d ERROS no total\n", errCount);
return 0;
}
regarding:
g->nos = (no_grafo **)malloc(sizeof(no_grafo*))`
the returned type is void* which can be assigned to any pointer. Casting just clutters the code and is error prone. Suggest removing the cast.
since no_grafo is a typedefstruct and you want to allocate enough memory for the struct, then remove the * from the parameter: sizeof(no_grafo*) should be: sizeof( no_grafo )
Always check (!=NULL) the returned value to assure the operation was successful. If not successful (==NULL) then call:
perror( "malloc failed" );
which will output to stderr both the error message "malloc failed" and the text reason the system thinks the error occurred.

fopen results in segfault

As in the headline.
Simple exercise, trying to learn structures and other essential c functionality.
Here is a structure containing a char[] and a number, I try to save its values in a file and read them back.
I read through a lot of topics concerning Seg.fault by fopen(), but can't find my mistake!
Someone here who knows why fopen() does crash in this instance?
Any suggestions and criticism on the matter is welcome!
The function where the Segfault happens is load():
void load(struct Telephon *structure, int *counter)
{
char filename[255];
char puffer[255], puffercpy[255];
int i, c, newline_count;
size_t strlaen;
FILE *datei=NULL;
char *token=NULL;
printf("\033[0;35mWelche Datei oeffnen?\033[0m\n");
scanf("%s", filename);
//emptystdin();
//strlaen=strlen(filename);
//printf("%d", strlaen);
//filename[strlaen+1] = '\0';
//printf("\n%s", filename);
datei = fopen(filename, "r");
if(datei==NULL)
{
printf("\033[0;31mKonnte Datei %s nicht oeffnen.\033[0m\n", filename);
}
else
{
while ( (c=fgetc(datei)) != EOF ) //count lines of file
{
if ( c == '\n' )
{
newline_count++;
}
}
for(i=0; i<=newline_count; i++) //get values in between ";"
{
fgets(puffer, 254, datei);
strcpy(puffercpy, puffer);
token = strtok(puffercpy, ";");
*counter = atoi(token);
token = strtok(NULL, ";");
strcpy(structure[i].name, token);
token = strtok(NULL, ";");
structure[i].nummer = atoi(token);
}
fclose(datei);
}
return;
}
The whole code, main is at the end:
telephonListen.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define MAX 100
struct Telephon
{
char name[210];
unsigned int nummer;
}TELE[MAX];
char* gotTime(char *timestrg)
{
time_t now;
now = time(NULL);
strftime (timestrg, 19, "%d.%m.%Y, %H:%M", localtime (&now));
return timestrg;
}
void printT(struct Telephon *structarray, int addcount)
{ int i;
if(addcount==0)
{
printf("\033[0;31mEs sind noch keine Eintraege vorhanden!\033[0m\n");
return;
}
else
{
for(i=0; i<addcount; i++)
{
printf("\nEintrag Nr.%d\n%s:\t%d\n",i+1, structarray[i].name, structarray[i].nummer);
}
return;
}
}
void eingabe(int num, struct Telephon *structarray)
{
size_t inputlen;
int check;
if(num>MAX)
{
printf("\033[0;31mMaximale Anzahl von Eintraegen erreicht!\033[0m\n");
return;
}
else
{
printf("\n\033[0;35mNamen eingeben:\t\033[0m");
//fgets(structarray[num].name, MAX, stdin);
fgets(structarray[num].name, 209, stdin);
inputlen=strlen(structarray[num].name);
structarray[num].name[inputlen-1]='\0';
printf("\n\033[0;35mNummer eingeben:\t \033[0m");
do
{
check = scanf("%10u", &structarray[num].nummer);
}while( getchar()!='\n');
fflush(stdin);
if(check==1)
{
printf("Ihr Kontakt wurde angelegt!\n%s:\t%u\n", structarray[num].name ,structarray[num].nummer);
}
else
{
printf("Fehler bei der Eingabe. Kontakt wurde nicht angelegt!");
return;
}
return;
}
}
void writeFile(struct Telephon *structure, char *zeitf, int counter)
{
char filename[255];
int i;
FILE *datei;
if(counter>0)
{
printf("\033[0;35mIn welche Datei soll das Telephonbuch geschrieben werden?\n(Achtung: Vorhandene Dateien werden ueberschrieben!)\t\033[0m\n");
scanf("%s", filename);
getchar();
datei = fopen(filename, "w");
if(NULL == datei)
{
printf("\033[0;31mKonnte Datei %s nicht öffnen.\033[0m\n", filename);
}
fprintf(datei, "Telephonverzeichnis vom %s\nNAME\t\t|NUMMER\n\n", zeitf);
for(i=0; i<counter; i++)
{
fprintf(datei, "%s\t\t|%d\n", structure[i].name, structure[i].nummer);
}
printf("\033[0;32mDatei gespeichert.\033[0m\n");
fclose(datei);
}
else
{
printf("\033[0;31mEs sind noch keine Eintraege vorhanden!\033[0m\n");
return;
}
return;
}
void change(struct Telephon *structure, int count)
{
int eintragnum;
if (count == 0)
{
printf("\033[0;31mEs sind noch keine Eintraege vorhanden!\033[0m\n");
return;
}
else
{
printT(structure, count);
printf("\033[0;31mWelcher Eintrag soll geaendert werden?\033[0m\n");
do
{
scanf("%d", &eintragnum);
}while(getchar()!='\n');
if(eintragnum<1||eintragnum>count)
{
printf("\033[0;31mBitte die Nummer [zwischen %d und %d]\n des zu aendernden Eintrags eingeben!\033[0m\n", 1, count);
}
else
{
eingabe(eintragnum-1, structure);
}
}
return;
}
void emptystdin()
{
int c;
while( ((c = getchar()) != EOF) && (c != '\n') );
}
void searchContact(struct Telephon *structure, int count)
{
char searchC;
int inputlen;
int i=0;
int countcompare;
if (count == 0)
{
printf("\033[0;31mEs sind noch keine Eintraege vorhanden!\033[0m\n");
return;
}
else
{
printf("Anfangsbuchstabe:\t");
scanf("%c", &searchC);
emptystdin();
for(i=0; i<count; i++)
{
if(structure[i].name[0]==searchC)
{
printf("Eintrag gefunden:\n");
printf("Nr. %d\nName:\t%s\nNummer:\t%u\n", i+1, structure[i].name, structure[i].nummer);
}
}
return;
}
}
void save(struct Telephon *structure, int counter)
{
char filename[255];
int i;
FILE *datei;
if(counter>0)
{
printf("\033[0;35mUnter welchem Dateinamen speichern?\n(Achtung: Vorhandene Dateien werden ueberschrieben!)\t\033[0m\n");
scanf("%s", filename);
emptystdin();
datei = fopen(filename, "w");
if(NULL == datei)
{
printf("\033[0;31mKonnte Datei %s nicht anlegen.\033[0m\n", filename);
}
for(i=0; i<counter; i++)
{
fprintf(datei, "%d;%s;%d\n", i+1, structure[i].name, structure[i].nummer);
}
printf("\033[0;32mDatei gespeichert.\033[0m\n");
fclose(datei);
}
else
{
printf("\033[0;31mEs sind noch keine Eintraege vorhanden!\033[0m\n");
}
return;
}
void load(struct Telephon *structure, int *counter)
{
char filename[255];
char puffer[255], puffercpy[255];
int i, c, newline_count;
size_t strlaen;
FILE *datei=NULL;
char *token=NULL;
printf("\033[0;35mWelche Datei oeffnen?\033[0m\n");
scanf("%s", filename);
//emptystdin();
//strlaen=strlen(filename);
//printf("%d", strlaen);
//filename[strlaen+1] = '\0';
//printf("\n%s", filename);
datei = fopen(filename, "r");
if(datei==NULL)
{
printf("\033[0;31mKonnte Datei %s nicht oeffnen.\033[0m\n", filename);
}
else
{
while ( (c=fgetc(datei)) != EOF ) //Zeilen in Datei zählen
{
if ( c == '\n' )
{
newline_count++;
}
}
for(i=0; i<=newline_count; i++) //CVS parsen/auslesen
{
fgets(puffer, 254, datei);
strcpy(puffercpy, puffer);
token = strtok(puffercpy, ";");
*counter = atoi(token);
token = strtok(NULL, ";");
strcpy(structure[i].name, token);
token = strtok(NULL, ";");
structure[i].nummer = atoi(token);
}
fclose(datei);
}
return;
}
int main(void)
{
int auswahl;
int count = 0;
char zeit[20];
char buffer[2];
struct Telephon *structptr; //malloc(MAX*(sizeof(TELE)));
structptr = TELE;
gotTime(zeit);
system("clear");
printf("Telephonkontaktverwaltung\t%s\n", zeit);
do
{
printf("\033[30;47m1: Kontakt hinzufuegen\t2: Kontakte anzeigen\n3: Kontakt aendern\t4: Als Datei speichern\n5. Kontakt suchen\n6. Als CVS sichern\t7. Aus CVS laden\n8. Beenden\nEine der Ziffern eingeben, mit Enter bestaetigen\033[0m\n");
/*
scanf("%d", &auswahl);
scanf("%c", &buffer);
fgets(buffer, 2, stdin);
if(isdigit(buffer[1]))
{
auswahl=atoi(buffer);
}
else
{
printf("Eine der Nummern eingeben um Aktion auszufuehren!\n");
}
do
{
scanf("%d", &auswahl);
}while(getchar()!='\n');
fgets(buffer, 2, stdin);
sscanf(buffer, "%d", &auswahl);
*/
scanf("%d", &auswahl);
emptystdin();
switch (auswahl)
{
case 1 : eingabe(count++, structptr);
break;
case 2 : printT(structptr, count);
break;
case 3 : change(structptr, count);
break;
case 4 : writeFile(structptr, gotTime(zeit), count);
break;
case 5 : searchContact(structptr, count);
break;
case 6 : save(structptr, count);
break;
case 7 : load(structptr, &count);
break;
case 8 : printf("ENDE\n");
break;
default : printf("Eine der Nummern eingeben um Aktion auszufuehren!\n");
break;
}
}while(auswahl!=8);
return EXIT_SUCCESS;
}
Use rewind().
Between the while() and for() loops, the file need to start at the beginning again.
while ( (c=fgetc(datei)) != EOF ) //count lines of file
{ ...}
rewind(datei);
for(i=0; i<=newline_count; i++) //get values in between ";"
{ ...}
Strongly suggest avoid using scanf() and fgets(,,stdin). Recommend one. Preferable fgets().
You likely want scanf(" %c", instead of scanf("%c",. (Add space).
Minor Idea:
Not that English is the be-all end-all language, but OP may want to consider something like
// Bold Red "Could not create file" EOL
const char *Err_FileCreation_format = "\033[0;31mKonnte Datei %s nicht anlegen.\033[0m\n"
printf(Err_FileCreation_format, filename);
// or
#define Err_FileCreation_fmt1 "\033[0;31mKonnte Datei "
#define Err_FileCreation_fmt2 " nicht anlegen.\033[0m\n"
printf(Err_FileCreation_fmt1 "%s" Err_FileCreation_fmt2, filename);
Assuming undefined behaviour hadn't been invoked prior to a call to fopen() the only way to make it crash is to pass it a non-initialised or non-0-terminated character array as file name or mode.
So to avoid this properly initialise all variables used to hold a file name and/or mode by declaring it like:
char filename[256] = "";
To avoid allowing scanf() to read in more then filenamecan hold do like this:
scanf("%255s", filename);
Update:
This code
while ( (c=fgetc(datei)) != EOF ) //count lines of file
{
if ( c == '\n' )
{
newline_count++;
}
}
reads until the end of the file.
So this code
for(i=0; i<=newline_count; i++) //get values in between ";"
{
fgets(puffer, 254, datei);
strcpy(puffercpy, puffer);
token = strtok(puffercpy, ";");
*counter = atoi(token);
token = strtok(NULL, ";");
strcpy(structure[i].name, token);
token = strtok(NULL, ";");
structure[i].nummer = atoi(token);
}
would not be able to read anything, as eof had already been reached.
However the code does not test whether fgets() might have failed but happily starts parsing what it didn't read and ... crashes during atoi()ing a token pointing to NULL.

C - printf("%s") show Symbols

I need your help because when I print the values ​​of atual->chave they return Symbols.
this is the code:
void mostrar(struct tLdde *l, int modo)
{
struct tItem *atual;
char *chave;
if(modo == CABECA)
{
atual = l->inicio;
while(atual != NULL)
{
chave = atual->chave;
printf("%s ", &chave);
atual = atual->proximo;
}
}
else
{
atual = l->final;
while(atual != NULL)
{
chave = atual->chave;
printf("%s ", &chave);
atual = atual->anterior;
}
}
printf("\n");
}
and this is the output:
Spea { Obam{ iPhoP{ Pott8{
use
printf("%s ", chave);
and not
printf("%s ", &chave);
remove the &

Resources