I have a segmentation fault in the moment of get the second file in the function imprimir, and i dont know whats happend, because he open and read the firts but not other file, is very confused for me, please help me
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char nombre[40];
int creditos;
float nota;
} curso;
int conteo(FILE *_entrada);
void semestre(FILE *_entrada,curso *_materias,int *_cantidad,int *_ganadas,int *_perdidas,float *_promedio);
void imprimir(curso *_materias,int *_cantidad,int *_ganadas, int *_perdidas,float *_promedio);
int main(int argc, char *argv[])
{
int ganadas=0;
int perdidas=0;
float promedio=0.0;
int cantidad=0;
char *archivoEntrada;
curso *materias;
printf("Archivo de entrada \n");
scanf("%s",archivoEntrada);
FILE *entrada;
entrada=fopen(archivoEntrada,"r");
if(entrada==NULL)
{
printf("No se logro abrir el archivo de entrada\n");
exit(EXIT_FAILURE);
}
cantidad=conteo(entrada);
printf("El numero de materias es: %d \n",cantidad);
materias=(curso *)malloc(sizeof(curso)*cantidad);
semestre(entrada,materias,&cantidad,&ganadas,&perdidas,&promedio);
imprimir(materias,&cantidad,&ganadas,&perdidas,&promedio);
free(materias);
}
int conteo(FILE *_entrada)
{
int i=0;
char auxiliar[40];
while(!feof(_entrada))
{
fgets(auxiliar,40,_entrada);
i++;
}
rewind(_entrada);
return i/3;
}
void semestre(FILE *_entrada,curso *_materias,int *_cantidad,int *_ganadas,int *_perdidas,float *_promedio)
{
int i=0;
int sumaCreditos=0;
float sumaNotas=0.0;
while(i<*_cantidad)
{
fscanf(_entrada, "%s", _materias->nombre);
fscanf(_entrada, "%d", &_materias->creditos);
sumaCreditos=sumaCreditos+(_materias->creditos);
fscanf(_entrada, "%f", &_materias->nota);
if((_materias->nota)>3.0)
{
*_ganadas=(*_ganadas)+1;
}
}
}
void imprimir(curso *_materias,int *_cantidad,int *_ganadas, int *_perdidas,float *_promedio)
{
fflush(stdin);
printf("Ganadas %d \n",*_ganadas);
printf("perdidas %d \n",*_perdidas);
printf("prom %f \n",*_promedio);
char *archivoSalida;
FILE *salida;
printf("Archivo de salida \n");
scanf("%s",archivoSalida);
salida=fopen(archivoSalida,"w");
if(salida==NULL)
{
printf("No se logro abrir el archivo de salida\n");
exit(EXIT_FAILURE);
}
//Implementacion imprimir en archivo salida.txt
}
You have
char *archivoSalida;
and then
scanf("%s",archivoSalida);
The problem here is that the pointer archivoSalida doesn't actually point anywhere special. Uninitialized local variables (like archivoSalida is) have an indeterminate value. Using them without initialization leads to undefined behavior, a very common cause of crashes.
Instead you might want to use a fixed-size array:
char archivoSalida[256];
...
scanf("%255s",archivoSalida);
Related
I'm new to C, I've already searched and I haven't found an answer, but I've been trying to get the program to give me a list with the name of the products typed in by the user followed by the sum of all prices and I've found the error:
clang-7 -pthread -lm -o main main.c
/tmp/main-7440c0.o: In function `main':
main.c:(.text+0x12b): undefined reference to 'N'
main.c:(.text+0x164): undefined reference to 'Digitanome'
main.c:(.text+0x17f): undefined reference to 'Lista'
clang-7: error: linker command failed with exit code 1 (use -v to see invocation)
exit status 1
The code I've been trying is this one:
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
extern char (N[][40]);
int i;
char p;
int cod,cont, soma2;
char soma[100];
int Digitanome( char [][40], int );
void Lista( char [100][40], int );
typedef struct {
char produto[30];
char seçao [30];
float preco;
int cargo;
}Supermercado;
Supermercado compra;
int main(void)
{
char Nome[100][40] = { '\0' };
int qtdNomes = 0;
soma2 = 0;
do{
printf("\n\nEm qual seção está seu produto?");
printf("\n1-Frutas \n2-Doces \n3-Material de Limpeza\n --> ");
scanf("%d",&cod);
if(cod == 1){
*compra.seçao = *strcpy(compra.seçao,"Frutas");
}
if(cod == 2){
*compra.seçao = *strcpy(compra.seçao, "Doces");
}
if(cod == 3){
*compra.seçao = *strcpy(compra.seçao,"Material de Limpeza");
}
int Digitanome(char N[][40], int i);
{
printf("Informe o produto que você quer nesta seção: \n");
scanf("%s", & *N[i]);
*compra.produto = Digitanome( Nome, qtdNomes );
Lista( Nome, qtdNomes );
return ++i;
}
return 0;
printf("Informe o preço do produto: \n");
scanf("%f", &compra.preco);
soma2 = soma2 + compra.preco;
printf("\nDeseja mais algum produto? \n4-Sim \n0-Não, sair \n --> ");
scanf("%d",&cont);
}while(cont == 4);
{
if (cont == 0)
printf("\nFIM DAS COMPRAS!\n");
void Lista(char p[100][40], int i);{
int j = 0;
for (; j < i; j++ )
printf("\nSeus produtos são:%s\n", compra.produto);
}
printf("Essa compra está custando: %i \n", soma2);
}
}
Can anyone explain to me what is happening and how to solve it?
Several problems:
extern char (N[][40]);
You declare N as extern without initialization so you would also need to delcare it in another module with initialization. But you don't actually ever use the variable N. You have N[][40] as an argument to Digitanome. Once you fix item numbers 2 and 3 below, you can remove extern char (N[][40]); completely.
You define Digitanome and Lista inside main(). You need to define them outside of main().
You have semicolons at the end of Digitanome and Lista function definitions. You need to remove those.
You have code following the return 0 statement.
You call Digitanome from inside Digitanome. That is probably not what you want.
Once you fix those problems, you will probably find more.
As Jim mentioned, there is some syntax error in your code you need to fix.
I could not understand the logic of your code so if you still need help, comment to me so that we can do it together!
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
extern char (N[][40]); int i; char p; int cod,cont, soma2; char soma[100];
int Digitanome( char [][40], int ); void Lista( char [100][40], int ); int qtdNomes = 0;
char Nome[100][40] = { '\0' };
typedef struct { char produto[30]; char seçao [30]; float preco; int cargo; }Supermercado;
Supermercado compra;
int main(void) {
soma2 = 0; do{
printf("\n\nEm qual seção está seu produto?");
printf("\n1-Frutas \n2-Doces \n3-Material de Limpeza\n --> ");
scanf("%d",&cod);
if(cod == 1){
*compra.seçao = *strcpy(compra.seçao,"Frutas");
}
if(cod == 2){
*compra.seçao = *strcpy(compra.seçao, "Doces");
}
if(cod == 3){
*compra.seçao = *strcpy(compra.seçao,"Material de Limpeza");
}
return 0;
printf("Informe o preço do produto: \n");
scanf("%f", &compra.preco);
soma2 = soma2 + compra.preco;
printf("\nDeseja mais algum produto? \n4-Sim \n0-Não, sair \n --> ");
scanf("%d",&cont); }while(cont == 4); {
if (cont == 0)
printf("\nFIM DAS COMPRAS!\n");
printf("Essa compra está custando: %i \n", soma2); } }
int Digitanome(char N[][40], int i)
{
printf("Informe o produto que você quer nesta seção: \n");
scanf("%s", & *N[i]);
*compra.produto = Digitanome( Nome, qtdNomes );
Lista( Nome, qtdNomes );
return ++i;
}
void Lista(char p[100][40], int i) { int j = 0; for (; j < i; j++ )
printf("\nSeus produtos são:%s\n", compra.produto); }
I have this code and I don't know why after, I ask if you want to introduce another student and I say 1 or 0 the program ends and said segmentation fault (core dumped).
I ask to introduce another student in _nodo *insertaEnLista
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct actividades
{
char tipoDeActividad[22];
char diaDeLaSemana[12];
char horaDeIncio[8];
char horaDeFin[8];
};
struct materias
{
char nombre[30];
char profesor[30];
char tipoDeMateria[20];
struct actividades *actividad;
};
struct alumnos
{
char nombre[30];
int cedula;
int telefono;
struct materias *materia;
struct alumnos *siguiente;
};
typedef struct alumnos _nodo;
_nodo *crearLista(_nodo *apuntador);
bool listaVacia(_nodo *apuntador);
_nodo *insetarEnLista(char nombre[], long cedula, long telefono, _nodo *apuntador);
void imprimirLista (_nodo *apuntador);
_nodo *crearNodo(char nombre[], long int cedula, long int telefono);
//AQUI SE CREA LISTA Y SE PONE PARA QUE APUNTE A NULL
_nodo *crearLista(_nodo *apuntador)
{
return (apuntador = NULL);
}
//ESTA FUNCION VERIFICA SI LA LISTA ESTA VACIA
bool listaVacia(_nodo *apuntador)
{
if (apuntador == NULL)
return (true);
else
return (false);
}
//AQUI SE CREA EL NUEVO NODO DE LA LISTA
_nodo *crearNodo(char nombre[], long cedula, long telefono)
{
_nodo *registroNuevo;
registroNuevo = (_nodo *) malloc(sizeof(_nodo));
printf("\n----NUEVO ELEMENTO----\n");
printf("NOMBRE: ");
fflush(stdin);
scanf("%s",nombre);
printf("CEDULA: ");
fflush(stdin);
scanf("%ld", &cedula);
printf("TELEFONO: ");
fflush(stdin);
scanf("%ld", &telefono);
fflush(stdin);
strcpy(registroNuevo->nombre, nombre);
registroNuevo->cedula = cedula;
registroNuevo->telefono = telefono;
registroNuevo->siguiente = NULL;
return registroNuevo;
}
//AQUI SE INSERTA EL NODO EN LA LISTA LUGEO DE SER CREADO POR LA FUNCION crearNodo
_nodo *insetarEnLista(char nombre[], long cedula, long telefono, _nodo *apuntador)
{
_nodo *registroNuevo, *apuntadorAuxiliar;
char respuesta,ch;
do
{
registroNuevo=crearNodo(nombre, cedula, telefono);
if (listaVacia(apuntador)) apuntador = registroNuevo;
else
{
apuntadorAuxiliar = apuntador;
while (apuntadorAuxiliar->siguiente != NULL)
apuntadorAuxiliar = apuntadorAuxiliar->siguiente;
apuntadorAuxiliar->siguiente = registroNuevo;
}
printf("\nPARA INGRESAR A OTRO ALUMNO MARQUE... 1");
printf("\nPARA SALIR MARQUE... '0'\n");
while((ch = getchar()) != EOF && ch != '\n');
scanf("%c", &respuesta);
fflush(stdin);
printf("RESPUESTA = %c", respuesta);
}while (strcmp(&respuesta, "1")==0);
return apuntador;
}
//IMPRIMIR LOS NODOS DE LA LISTA
void imprimirLista (_nodo *apuntador)
{
_nodo *apuntadorAuxiliar;
apuntadorAuxiliar = apuntador;
if (apuntador == NULL)
printf("NO HAY ELEMENTOS EN LA LISTA \n");
else
{
while(apuntador != NULL)
{
printf(" \n------------NODO-------------- ");
printf("\nNOMBRE: %s \n\n", apuntadorAuxiliar->nombre);
printf("\n\nCEDULA: %d \n", apuntadorAuxiliar->cedula);
printf("\nTELEFONO: %d \n", apuntadorAuxiliar->telefono);
apuntadorAuxiliar = apuntadorAuxiliar->siguiente;
}
}
return;
}
int main()
{
/*printf("INTRODUZCA LOS NUMEROS DE CEDULA QUE DESEA IMPRIMIR \n");*/
_nodo *inicioLista;
int cedula;
int telefono;
char nombre[20];
inicioLista = crearLista(inicioLista);
inicioLista = insetarEnLista(nombre, cedula, telefono, inicioLista);
imprimirLista(inicioLista);
return 0;
}
How can I do to fix the problem.
You should step through the code in a debugger and look at the variables at each step to determine the line of code that is causing the issue.
Here is one issue, there may be others.
In this line
}while (strcmp(&respuesta, "1")==0);
you are using strcmp with a variable (respuesta) that contains a single character. strcmp is expecting a null terminated string (an array of characters with a zero byte at the end). As you may not have a zero byte after the variable, this may cause strcmp to read memory that it shouldn't (this is a buffer overrun)
Much simpler to just use:
}while (respuesta == '1');
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have some troubles when executing my program, some characters appeared out of nowhere ( especially this one : and sometimes others) , I don't understand where is the problem and how to delet them.
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <magic.h>
#include <string.h>
typedef struct Chaine
{
char * Lachaine;
int Taille_C;
} Chaine ;
char * test ( char*);
void ReccuperationTexte(char** txt);
void afficheTable2D(int** Table, Chaine * Tab_du_texte );
int * Tab_fin( int** Table, Chaine * Tab_du_texte );
char*Le_suff(int* tab_suf,Chaine *);
int ** Table2D ( Chaine *);
char* copietext ( char * , int );
int taille_texte ( char * fichier);
int main (void)
{
system("ls");
Chaine *Tab_du_texte=NULL;
Tab_du_texte=(Chaine*)malloc(sizeof(Chaine));
Tab_du_texte->Lachaine=NULL;
Tab_du_texte->Taille_C=0;
char fichier[50];
char * restest=NULL;
char * LeSuffixe=NULL;
LeSuffixe=(char*)malloc(sizeof(char)*50);
restest=(char*)malloc(sizeof(char)*15);
int **Table=NULL;
int* Tab_final=NULL;
int i;
Tab_final=(int*) malloc (sizeof(int)*100);
printf("tapez le nom du fichier s'il vous plais: ");
scanf(" %s",fichier);
restest=test(fichier);
while(strcmp( restest, "ASCII text") != 0 || strcmp( restest, "rien")==0)
{
printf("il ne s'agit pas d'un fichier texte ou bien le fichier n'existe pas.\nVeillez choisir un autre:");
scanf(" %s",fichier);
restest=test(fichier);
}
printf("vous avez bien selectionné un fichier texte.\n");
Tab_du_texte->Taille_C= taille_texte (fichier);
/*copie du fichier texte dans un tab dynamique*/
Tab_du_texte->Lachaine=(char*)malloc(sizeof(char)*Tab_du_texte->Taille_C);
Tab_du_texte->Lachaine= copietext (fichier, Tab_du_texte->Taille_C);
printf("La chaine est: %s",Tab_du_texte->Lachaine);
fflush(stdin);
/*creation du tableau 2D */
Table=Table2D(Tab_du_texte);
afficheTable2D(Table,Tab_du_texte);
Tab_final=Tab_fin(Table,Tab_du_texte);
for(i=0;i<Tab_du_texte->Taille_C;i++)
printf("%d",Tab_final[i]);
LeSuffixe=Le_suff(Tab_final,Tab_du_texte);
printf("Le suff est:%s",LeSuffixe);
for(i=0; i<Tab_du_texte->Taille_C; i++)
{
free(Table[i]);
}
free(Table);
free(restest);
return 0;
}
char * test ( char* ftest)
{
magic_t cookie;
const char *description;
char *res;
res=(char*)malloc(sizeof(char)*15);
cookie = magic_open(MAGIC_NONE);
if (cookie != NULL)
{
/* on va charger la base de données */
if (magic_load(cookie, NULL) == 0)
{
description = magic_file(cookie, ftest);
if (description != NULL && strlen(description)<15)
strcpy(res,description);
else
{
res="rien";
}
magic_close(cookie);
}
else
fprintf(stderr, "error loading the magic database\n");
}
return res;
}
int taille_texte ( char * fichier)
{
Chaine *Tab_Texte=NULL;
Tab_Texte=(Chaine*)malloc(sizeof(Chaine));
FILE* Texte= NULL;
Texte = fopen(fichier, "r");
fseek(Texte, 0, SEEK_END);
Tab_Texte->Taille_C=ftell(Texte);
return Tab_Texte->Taille_C;
}
char * copietext ( char * fichier, int taille_C)
{
char *Tab_Texte=NULL;
FILE* Texte= NULL;
Texte = fopen(fichier, "r");
fseek(Texte, 0, SEEK_SET);
Tab_Texte=(char*)malloc(sizeof(char)*taille_C);
fread(Tab_Texte,sizeof(char)*(taille_C),1,Texte);
return Tab_Texte;
}
int ** Table2D ( Chaine * Tab_du_texte)
{
int i,j,k,t;
int** Table=NULL;
t=Tab_du_texte->Taille_C;
Table=(int**)malloc(sizeof(int*)*t);
for(j=0;j<t;j++)
Table[j]=(int*)malloc(sizeof(int)*t);
for(j=0; j<t; j++) // Initialisation de la première ligne des i
{
Table[0][j]=0;
}
for(i=1; i<t ;i++)
{
for(k=0; k<i; k++)
{
Table[i][k]=0;
}
for(j=i; j<t; j++)
{
if(((Tab_du_texte->Lachaine[i]>=32 && Tab_du_texte->Lachaine[i]<=126) && (Tab_du_texte->Lachaine[j]>=32 && Tab_du_texte->Lachaine[j]<=126)) && Tab_du_texte->Lachaine[i-1]==Tab_du_texte->Lachaine[j])
{
Table[i][j]=Table[i-1][j-1]+1;
}
else
{
Table[i][j]=0;
}
}
}
return Table;
}
void afficheTable2D(int** Table, Chaine * Tab_du_texte)
{
int i, j,t;
t=Tab_du_texte->Taille_C;
for(i=0; i<t; i++)
{
for(j=0; j<t; j++)
{
if(i>j)
printf(" ");
else
printf("%d",Table[i][j]);
}
printf("\n");
}
printf("\n");
}
int * Tab_fin(int** Table,Chaine * Tab_du_texte)
{
int i,j,t;
t=Tab_du_texte->Taille_C;
int max =0;
int * Tab_suff=NULL;
Tab_suff=(int*)malloc(sizeof(int)*t);
Tab_suff[0]=0;
for (j=0;j<t;j++)
{
for(i=0;i<=j;i++)
{
if (Table[i][j]>max)
max= Table[i][j];
}
Tab_suff[j]=max;
max=0;
}
return Tab_suff;
}
char*Le_suff(int* tab_suf,Chaine * Tab_du_texte)
{
int max,i,max_i,t;
char* suffixe=NULL;
t=Tab_du_texte->Taille_C;
max=0;
for(i=0;i<t;i++)
{
if(max<tab_suf[i])
{
max=tab_suf[i];
}
}
for(i=0;i<t;i++)
{
if(max==tab_suf[i])
max_i=i;
}
suffixe=(char*)malloc(sizeof(char)*max);
strncpy(suffixe,&Tab_du_texte->Lachaine[max_i-(max-1)],max);
printf("\n%s\n",suffixe);
return suffixe;
}
Sorry, the code is not well identified but I will fix it later. ( the program is in french )
Pretty difficult to read french c-code.... Anyway, I would take a second look at the fread in copietext. I don't think that will give you a zero-terminated string.
I have few error commented after this text, i don't get what the compiler is trying to say me, the last function is in to do list i hope that's not the problem, the problem is i want to ask the user for 2 chars after that its send to a function who will compare the strings as a password and a login if the strings are the same, the program continues.
\\initializing argument 1 of int consultar(char, char)\\
\\invalid conversion from char*' to `char' \\
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void introducir_datos (struct agenda cliente[30]);
void mostrar_datos(struct agenda cliente[30]);
char consultar(char login,char password);
struct agenda{
char nombre[10];
char apellido[10];
int edad;
char direccion[20];
int codigo_postal;
};
int main(void)
{
struct agenda cliente[30];
int menu;
char con[3],login[8], password[8];
puts("\n=== Hola bienvenido a nuestra agenda en C ===\n");
puts("Login:");
gets(login);
puts("Password:");
gets(password);
**consultar(login, password);**
while ( menu != 3){
puts("\nQue quieres hacer?\n");
puts("[1]Insertar datos\n[2]Mostrar datos\n[3]Salir del programa\n");
scanf("%d", &menu);
switch(menu){
case 1:
introducir_datos(cliente);
break;
case 2:
mostrar_datos(cliente);
break;
default:
system("cls");
puts("~~~ Opcion incorrecta ~~~");
}
}
}
void introducir_datos (struct agenda cliente[30]){
int x = 0;
puts("\n=== Bienvenido a la introduccion de datos ===\n");
fflush(stdin);
system("pause");
system("cls");
puts("\nDime el nombre:\n");
fflush(stdin);
gets(cliente[x].nombre);
puts("\nDime el apellido:\n");
fflush(stdin);
gets(cliente[x].apellido);
puts("\nDime la edad:\n");
fflush(stdin);
scanf("%d",&cliente[x].edad);
puts("\nDime la direccion:\n");
fflush(stdin);
gets(cliente[x].direccion);
puts("\nDime el codigo postal:\n");
fflush(stdin);
scanf("%d",&cliente[x].codigo_postal);
x++;
}
void mostrar_datos(struct agenda cliente[30]){
for(int i=0;i<20;i++){
int x = 0;
printf("El nombre: %s \nEl apellido: %s\nEl edad: %d\nEl direccion: %s\nEl codigo postal: %d\n", cliente[x].nombre,cliente[x].apellido,cliente[x].edad,cliente[x].direccion,cliente[x].codigo_postal);
}
}
int consultar(char login, char password){
}
You need to change the consultar function (definition and implementation):
int consultar(char login, char password)
to:
int consultar(char *login, char *password)
If you use (char login, char password), it's looking for a single character. Since, by calling it with consultar(login, password);, you're using pointers to char arrays (simplified explaination), you're getting the error.
EDIT As pointed out by user "Namfuak", you should decide whether the function returns a char or an int, and have both definition and implementation be consistent.
Could you explain me why after a rewind(f) in the function "recuperationdeNS", I have a Segmentation Fault ?
The second printf in the function "recuperationdeNS" doesn't appear. The segmentation fault stopped the program before.
I'm sure that the name of the file is ok.
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include"procedurecommune.h"
#include"procedureGenA.h"
#include"procedureGenO.h"
void ouvrir_fic(FILE** f, char* nom,char* type)
{
*f=fopen(nom,type);
if(f==NULL)
{
printf("probleme lecture ou ecriture du fichier : %s\n",nom);
exit(2);
}
}
int recuperationdeNS(FILE* fichG)
{
printf("aloooooooooo\n");
int i, N;
char chaine [2000];
rewind(fichG);
printf("aloooooooooo\n");
for(i=0;i<2;i++) // on saute les lignes de commentaires
{
fgets(chaine, sizeof chaine, fichG);
printf("chaine :%s\n",chaine);
}
fscanf(fichG, "%d",&N); // recuperation de N
return (N);
}
void recuperationnomfichiergena(FILE* fichG, char** NomFichierGenA, int nbligneasauter)
{
int i,c,iemecaractereligne;
rewind(fichG);
char chaine [Nmcl];
for(i=0;i<nbligneasauter;i++) // on saute les lignes de commentaires
{
fgets(chaine, sizeof chaine, fichG);
}
*NomFichierGenA=(char*) malloc (sizeof(char)*Nmcl);
fgets(chaine, sizeof chaine, fichG);
iemecaractereligne=0;
c=chaine[iemecaractereligne];
while(c != '\n')
{
c=chaine[iemecaractereligne];
if(c !='\n')
{
(*NomFichierGenA)[iemecaractereligne]=c;
}
iemecaractereligne++;
}
}
int determinationtypedegenchoisi(FILE* fichG);
int recuperationdeN(FILE* fichG);
void recuperationtabentiergenencours(FILE* fichG,int* genencours, int N);
void recuperationnomfichiergena(FILE* fichG, char ** nomfich,int nbligneasauter);
void main(int args, char **argv)
{
FILE * fichG=NULL;
FILE * fichM=NULL; //fichier contenant le contexte
FILE * fichMgenParAtt=NULL; //fichier contenant le contexte pregeneralise par attribut
FILE * fichGA=NULL; //fichier contenant la matrice de generalisation attribut
FILE * fichGO=NULL;
int** Matricegenereextraite;
int typedegen;
int i,nbligneMat,nbcolonneMat,nbgroupegeneralisant1,nbgroupegeneralisant2;
char NomUniqueFichierGen[Nmcm];
char chaine[Nmcl];
char* NomFichGenExtraitA;
char* NomFichGenExtraitO;
char* NomFichGenExtraitFinale;
char* NomFichierGenA ;
char* NomFichierGenO;
char* chaineNva;
char* chaineNvo;
int Na, No;
int N, Ni;
int* nbgroupegeneralisant;
int nbgroupegeneralisantmax;
const int nbligneenteteGparun = 5;//nombre de ligne pour acces nom fichier de gen attribut
const int nbligneenteteGpardeux = 8;//nombre de ligne pour acces nom fichier de gen objet
int* genencours;
NomFichGenExtraitA=argv[3];
NomFichGenExtraitO=argv[4];
NomFichGenExtraitFinale=argv[5];
chaineNva= argv[6];
chaineNvo= argv[7];
char dernierephrase[]="Name_of_dataset\n";
char* nomsdesobjets;
char** nomsdesgroupes;
char* nomsdesattributs;
int*** Matrice;
//Nva=chaineNva[0]-'0';
//Nvo=chaineNvo[0]-'0';
/// ouverture des fichiers
ouvrir_fic(&fichG, argv[2],"r");
ouvrir_fic(&fichM, argv[1],"r");
///////////////////////////////////////////////
//info du fichier Gen.txt
typedegen=determinationtypedegenchoisi(fichG);
printf("typedegen: %d\n",typedegen);
N=recuperationdeN(fichG);
printf("N: %d\n",N);
allocationdynamiquetableauunedimdentier(&genencours, N);
recuperationtabentiergenencours(fichG,genencours,N);
///////////////////recuperation choix de gen
//////////////////////////////////////////////////
//info du fichier Matrice.txt
nblignecolonneMat(fichM,&nbligneMat,&nbcolonneMat,dernierephrase);
printf("nbligneMat :%d, nbcolonneMat :%d\n",nbligneMat, nbcolonneMat);
///lecture du noms des objets et des attributs
objetsetattributs(fichM, &nomsdesobjets,&nomsdesattributs, dernierephrase);
printf("nomsdesO : %s\n",nomsdesobjets);
printf("nomsdesA : %s\n",nomsdesattributs);
//allocation dynamique
allocationdynamiquetableautroisdimdentier(&Matrice,N,nbligneMat,nbcolonneMat);
/// recuperation de la matrice de depart
recuperationmatrice (fichM, Matrice[0], nbligneMat, nbcolonneMat);
printf("\nMatrice 0:\n");
affichageMatrice(0, nbligneMat, 0, nbcolonneMat, Matrice[0]);
typedegen=1;
if(typedegen==1)
{
//////////////////////////////////////////
//info du fichier genO.txt
recuperationnomfichiergena(fichG, &NomFichierGenO,nbligneenteteGpardeux);
printf("fichier de generalisation utilise :%s\n ",NomFichierGenO);
ouvrir_fic(&fichGO, NomFichierGenO,"r");
No=recuperationdeNS(fichGO);
printf("No :%d\n",No);
}
}
Your file open check in ouvrir_fic() is faulty:
void ouvrir_fic(FILE** f, char* nom,char* type)
{
*f=fopen(nom,type);
if(f==NULL)
{
printf("probleme lecture ou ecriture du fichier : %s\n",nom);
exit(2);
}
}
You should be checking whether *f is NULL; you've already assumed that f is not null when you made the assignment.
Since the file failed to open, you have a null pointer in *f.
I'd probably use:
FILE *ouvrir_fic(const char *nom, const char *mode)
{
FILE *fp = fopen(nom, mode);
if (fp == NULL)
{
fprintf(stderr, "probleme lecture ou ecriture du fichier: %s\n", nom);
exit(2);
}
return(fp);
}
This may be contributing to the problem:
*f=fopen(nom,type);
if(f==NULL)
The if check does not check if the file was opened (only checks if the f argument is not null, after it has been used). If fopen() fails the file pointer will be NULL and it will be undetected. The check should be:
if (*f == NULL)