i have this function that extract the first name and the gendre form a file combined and then seperate them
for example the function extract "Aaliyah,F" and the separate them as prenom = Aaliyah and genre = F
the problem is that the function does not update the genre value and still at NULL
so for this code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int AleaNombre(int min, int max) {
return (rand() % (max - min + 1)) + min;
}
void recuperer_prenom(char genre , char prenom[20] ) {
FILE* f2 = fopen("C:\\Users\\PC PRO DZ\\Desktop\\Projects\\C\\TP essai\\prenom.txt", "r");
fseek(f2, 0, SEEK_END);
int length = ftell(f2);
fseek(f2, 0, SEEK_SET);
char line1[length + 1];
fgets(line1, length + 1, f2);
int i = AleaNombre(1, 100);
int cpt = 0;
char* tok = strtok(line1, " ; ");
cpt++;
while (cpt != i) {
tok = strtok(NULL, " ; ");
cpt++;
}
//separer le prenom et le genre tel que prenom,genre et le genre est le dernier caractere en utilisant strtok
char* tok2 = strtok(tok, ",");
strcpy(prenom, tok2);
tok2 = strtok(NULL, ",");
genre = tok2[0];
printf("%s %c", prenom, genre); // the result is for example: "Aaliyah F"
rewind(f2);// ^ ^
fclose(f2);// |prenom| |genre|
}
int main () {
srand (time(NULL));
char prenom[20];
char genre;
recuperer_prenom(genre, prenom);
printf ("%s %c", prenom, genre);// however the result here is "Aaliyah"
return 0;
}
i tried changing the way that the prenom and genre are separated and change the type of genre from char to a sting but didn'f fixe it
I have removed the random part and created a struct to store your fields:
You should pass by reference as said in comment
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAXLINE 256
typedef struct data {
char prenom[20];
char genre;
} data;
void recuperer_prenom(data *d) {
FILE* f2 = fopen("prenom.txt", "r");
char line1[MAXLINE];
fgets(line1, MAXLINE, f2);
char* tok = strtok(line1, " ; ");
//separer le prenom et le genre tel que prenom,genre et le genre est le dernier caractere en utilisan>
char* tok2 = strtok(tok, ",");
strcpy(d->prenom, tok2);
tok2 = strtok(NULL, ",");
d->genre = tok2[0];
printf("%s %c\n", d->prenom, d->genre); // the result is for example: "Aaliyah F"
fclose(f2);// |prenom| |genre|
}
int main () {
data d;
recuperer_prenom(&d);
printf ("%s %c\n", d.prenom, d.genre);// however the result here is "Aaliyah"
return 0;
}
I am having trouble reading from a bin file.
I am recording some text in binary (correctly i think), but my code isn't able to read the text I wrote and print it in the console. When i open the file the information is there (this document is use to storage the information from the client and the login access) and i can login, but when i try to read and print in console it doesn't show me.
I am using a struct to get the values from the document, and then i open the document "fopen()" but when i try to read with the "fread()" in a "while" I don't get in, the print don't give me the right information
I try to reduce as much i could of the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <dir.h>
#include <unistd.h>
#include <time.h>
#include <conio.h>
#define SIZE 1000
typedef struct
{
char id[10];
char nome[100];
char passe[100];
}Pacient;
Pacient p1;
FILE* filepaciente;
//variables
char tmpnome[100], tmppassword[100];
//variable for path
char nomedoc[15];
char pasta[250];
char sessionName[15];
char tmp_name[15];
char fullpath[200];
char tmp_nome[15];
void vedocumento(int* i, char* line, char pacienteData[])
{
// DEFINE A VARIÁVEL USERDATA COMO UMA STRING VAZIA
strcpy(pacienteData, "");
// IF FINDS "|", GO TO THE NEXT CHARACTER
if (line[*i] == '|')
{
(*i)++;
}
//WHEN THE CHARACTER IS DIFERENT THEN |, ADD THAT CHARACTER TO THE ARRAY USERDATA
while (line[*i] != '|') // *i = 0
{
strncat(pacienteData, &line[*i], 1); // userData = "" ; userData = userData + carater
(*i)++;
}
}
findpath()
{
//PROCURA O CAMINHO ONDE SE ENCONTRA O PROJETO
if (getcwd(pasta, sizeof(pasta)) == NULL)
{
printf("ERROR!\n");
}
else
{
strcat(pasta, "\\file\\");
//CRIA O FICHEIRO COM O NUMERO DE INTERNO
strcpy(nomedoc, strcat(tmp_nome, ".bin"));
//JUNTA O CAMINHO COMPLETO AO NOME DO FICHEIRO
strcat(pasta, nomedoc);
strcpy(fullpath, pasta);
}
}
int main() //where i write in the bin file
{
//GETTING REGISTRY DATA
fflush(stdin); //para ir so buscar os dados
printf("\nName pacient: ");
scanf("%[^\n]", p1.nome);
printf("\nPassword do pacient %s: ", p1.nome);
scanf("%s", p1.passe);
printf("\nID pacient %s: ", p1.nome);
scanf(" %s", p1.id);
strcpy(tmp_nome, p1.nome);
strcpy(tmp_nome, strlwr(tmp_nome));
findpath();
if (access(fullpath, F_OK) == 0)
{
//IF EXISTS
printf("Este nome de utilizador já foi registado! Por favor, tente novamente!\n");
}
else
{
// IF DOESN'T EXIST
filepaciente = fopen(fullpath, "wb");
if (filepaciente == NULL)
{
printf("\nerror\n");
}
//size_t elements_written = fwrite(&p1, sizeof(Paciente), 1, filepaciente);
//PRINTING ON FILE
fprintf(filepaciente, "%s|%s|%s\n", p1.nome, p1.passe, p1.id);
fclose(filepaciente);
}
//WHERE I WANT TO PRINT ON THE CONSOLE
{
printf("Name do pacient: ");
scanf(" %[^\n]", tmpnome);
strcpy(tmp_nome, tmpnome);
strcpy(tmp_nome, strlwr(tmp_nome));//this is to get the name of the document
findpath(); //Find the path to the document
if (access(fullpath, F_OK) == 0)
{
filepaciente = fopen(fullpath, "rb"); //Open the document
Pacient pacient[100];
char line[SIZE];
int nline = 0;
fgets(line, SIZE, filepaciente);
int i = 0;
vedocumento(&i, line, pacient[nline].nome);
vedocumento(&i, line, pacient[nline].passe);
nline++;
//LOOP TO CHECK
for (i = 0; i < 1; i++)
{
if (strcmp(tmpnome, pacient[i].nome) == 0)
{ //WRITE INFO
char buf[SIZE];
if (filepaciente == NULL)
{
printf("\nERRO OPENING\n");
}else printf("\nOPEN THE FILE\n");
//IF I PUT "==1" DON'T GET IN THE WHILE
while( fread(&p1, sizeof(p1), 1, filepaciente) == 1)
{
printf("%c", p1); //NOT SURE IF THIS IS CORRECT
}
}
}
}
}
}
I'm creating a program in C. I want this program to invert a txt file, avec geojson coordinates.
The program is running good, but when the txt file is too long, the programe crash....!
I think there is a problem with the memory but i don't find how to solucionate it.
Thanks in advance !
There my main.c :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pile.h"
#include "pile_function.h"
#define TAILLE_MAX 5000 // Tableau de taille 1000
int main(int argc, char *argv[]) {
FILE* fichier = NULL;
FILE* fichier_creer = NULL;
char chaine[TAILLE_MAX] = ""; // Chaîne vide de taille TAILLE_MAX
char concat[TAILLE_MAX] = "";
char final[TAILLE_MAX] = "";
const char s[2] = "]";
char *token = malloc(sizeof(*token));
Pile *tas;
if ((tas = (Pile *) malloc (sizeof (Pile))) == NULL)
return -1;
initialisation (tas);
fichier = fopen(argv[1], "r+");
if (fichier != NULL)
{
// On peut lire et écrire dans le fichier
printf("Ouverture du fichier\n");
fgets(chaine, TAILLE_MAX, fichier);
fichier_creer = fopen("Fichier_Inverser.txt", "a+");
if (fichier != NULL)
{
printf("Ouverture du fichier_creer\n");
/* get the first token */
token = strtok(chaine, s);
/* walk through other tokens */
while( token != NULL )
{
strcpy(concat, token);
strcat(concat, s);
empiler(tas, concat);
token = strtok(NULL, s);
memset (concat, 0, sizeof (concat));
}
while( tas->taille != 0 )
{
strcpy (final, depiler(tas));
fputs(final, fichier_creer);
}
printf("\nFichier mise a jour\n");
fclose(fichier_creer);
printf("\nFermeture du fichier du fichier_creer\n");
}
else
{
printf("Impossible d'ouvrir le fichier_creer");
}
fclose(fichier);
printf("Fermeture du fichier du fichier\n");
}
else
{
printf("Impossible d'ouvrir le fichier");
}
return EXIT_SUCCESS;
}
There is my pile.h :
typedef struct ElementListe{
char *donnee;
struct ElementListe *suivant;
} Element;
typedef struct ListeRepere{
Element *debut;
int taille;
} Pile;
/* initialisation */
void initialisation (Pile *tas);
/* EMPILER*/
int empiler (Pile *tas, char *donnee);
/* DEPILER*/
char *depiler (Pile *tas);
/* Affichage de élément en haut de la pile (LastInFirstOut) */
#define pile_donnee(tas) tas->debut->donnee
/* Affiche la pile */
void affiche (Pile *tas);
There is my pile_function.h:
void initialisation (Pile * tas){
tas->debut = NULL;
tas->taille = 0;
}
int empiler (Pile * tas, char *donnee){
Element *nouveau_element;
if ((nouveau_element = (Element *) malloc (sizeof (Element))) == NULL)
return -1;
if ((nouveau_element->donnee = (char *) malloc (50 * sizeof (char))) == NULL)
return -1;
strcpy (nouveau_element->donnee, donnee);
nouveau_element->suivant = tas->debut;
tas->debut = nouveau_element;
tas->taille++;
}
char *depiler(Pile *pile)
{
if (pile == NULL)
{
exit(EXIT_FAILURE);
}
char *chaine = malloc(sizeof(*chaine));
Element *elementDepile = pile->debut;
if (pile != NULL && pile->debut != NULL)
{
strcpy (chaine, elementDepile->donnee);
pile->debut = elementDepile->suivant;
free(elementDepile);
}
pile->taille--;
return chaine;
}
void affiche (Pile * tas){
Element *courant;
int i;
courant = tas->debut;
for(i=0;i<tas->taille;++i){
printf("%s\n", courant->donnee);
courant = courant->suivant;
}
}
There is for exemple a list of coordinate, it doesn't work :
[2.2528324,49.0413749],[2.2530099,49.0409694],[2.2529714,49.0409477],[2.2529531,49.040845],[2.2528231,49.040697],[2.2525572,49.0405152],[2.2521051,49.0402405],[2.2518017,49.0400133],[2.2515308,49.0397237],[2.2514333,49.0395455],[2.2514103,49.0394521],[2.2514134,49.0393256],[2.25172,49.0383752],[2.2517745,49.0380228],[2.2518929,49.0377766],[2.2520333,49.0375694],[2.2522566,49.0373093],[2.2523922,49.0372076],[2.2525084,49.036936],[2.2528797,49.0363597],[2.2529077,49.0362346],[2.2528555,49.0359416],[2.2527984,49.0358494],[2.2527631,49.0358471],[2.2494004,49.0368099],[2.2445056,49.0382113],[2.2438535,49.0351289],[2.2434025,49.0334159],[2.2433668,49.0333207],[2.2424539,49.0292753],[2.242455,49.0290301],[2.2425994,49.0285152],[2.2425996,49.0284322],[2.241938,49.0267597],[2.241008,49.0254301],[2.2405995,49.0251103],[2.2405338,49.0250148],[2.2404128,49.0247205],[2.2403438,49.0244781],[2.2403436,49.0243775],[2.239998,49.0235028],[2.2399302,49.0233991],[2.2398091,49.0233274],[2.2397032,49.0232808],[2.2395594,49.0232176],[2.2394263,49.0231172],[2.2393327,49.0230396],[2.2392098,49.0229535],[2.2387176,49.0225323],[2.238216,49.0221354],[2.237813,49.0218217],[2.2375089,49.0214585],[2.2373633,49.0215158],[2.2371741,49.0213435],[2.2364466,49.0204618],[2.2363631,49.0202973],[2.2359734,49.0197239],[2.2358766,49.0195764],[2.23573,49.0192646],[2.2356873,49.0192694],[2.235498,49.0189371],[2.2354933,49.0189123],[2.2352065,49.0184121],[2.23519,49.0184137],[2.2350145,49.0184304],[2.2348705,49.0184441],[2.2342795,49.0177464],[2.2340851,49.017802],[2.2338829,49.0175392],[2.2338473,49.017546],[2.2331775,49.0168764],[2.2327003,49.0163514],[2.2326684,49.0163499],[2.231627,49.0154023],[2.2312705,49.0150763],[2.2311292,49.0149744],[2.2302659,49.0144945],[2.2301856,49.0144539]
But with the same list but short , it works :
[2.2528324,49.0413749],[2.2530099,49.0409694],[2.2529714,49.0409477],[2.2529531,49.040845],[2.2528231,49.040697],[2.2525572,49.0405152],[2.2521051,49.0402405],[2.2518017,49.0400133],[2.2515308,49.0397237],[2.2514333,49.0395455],[2.2514103,49.0394521],[2.2514134,49.0393256],[2.25172,49.0383752],[2.2517745,49.0380228],[2.2518929,49.0377766],[2.2520333,49.0375694],[2.2522566,49.0373093],[2.2523922,49.0372076],[2.2525084,49.036936],[2.2528797,49.0363597]
I'm a begineer..so maybe i'm not doing it good.
Thanks you for your reply.
Jordan
char *chaine = malloc(sizeof(*chaine)); => Here sizeof(*chaine) == 1 because type is char * so pointed type is char and sizeof(char) == 1. You probably want char *chaine = (char *) malloc(strlen(elementDepile->donnee) * sizeof(char));
– Fefux
In the function imprimir I have a problem when I do the fprintf in a file, because _materias->nombres does not return the value, for this reason, the text not show this information, please help because i don't know what is happening, if other person know how to create the in the struct nombre in array is better, because i don't do this for reason of the strtok because he return a char pointer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *nombre;
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[256];
curso *materias;
printf ("Archivo de entrada \n");
scanf ("%255s", 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);
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;
char auxiliar2[100];
char *token;
fgets (auxiliar2, 100, _entrada);
while (i < *_cantidad) {
fgets (auxiliar2, 100, _entrada);
token = strtok (auxiliar2, ":");
token = strtok (NULL, ":");
(_materias->nombre) = token;
fgets (auxiliar2, 100, _entrada);
token = strtok (auxiliar2, ":");
float val2 = atof (strtok (NULL, ":"));
(_materias->nota) = val2;
fgets (auxiliar2, 100, _entrada);
token = strtok (auxiliar2, ":");
float val = atoi (strtok (NULL, ":"));
(_materias->creditos) = val;
sumaCreditos = sumaCreditos + (_materias->creditos);
if ((_materias->nota) < 3.0) {
*_perdidas = (*_perdidas) + 1;
}
else {
*_ganadas = (*_ganadas) + 1;
}
sumaNotas = sumaNotas + ((_materias->nota) * (_materias->creditos));
i++;
*_materias++;
}
*_promedio = (sumaNotas / sumaCreditos);
}
void imprimir (curso * _materias, int *_cantidad, int *_ganadas,
int *_perdidas, float *_promedio)
{
char archivoSalida[256];
FILE *salida;
printf ("Archivo de salida \n");
scanf ("%255s", archivoSalida);
salida = fopen (archivoSalida, "w");
if (salida == NULL) {
printf ("No se logro abrir el archivo de salida\n");
exit (EXIT_FAILURE);
}
int i = 0;
fprintf (salida, "Archivo de Salida: \n");
fprintf (salida, "Materia\tNota\tCreditos \n");
while (i < *_cantidad) {
fprintf (salida, "%s\t%f\t%d \n", (_materias->nombre),
(_materias->nota), (_materias->creditos));
*_materias++;
i++;
}
fprintf (salida, "\nTotal de materias: %d \n", *_cantidad);
fprintf (salida, "Materias ganadas: %d \n", *_ganadas);
fprintf (salida, "Materias perdidas: %d \n", *_perdidas);
fprintf (salida, "Promedio ponderado: %f \n", *_promedio);
}
I'm trying to read a file like this:
nInp=20
nOut=1
NLaye=3
hid=30
er=0.001
epo=100
epoRep=100
pscpa=0
tip=Aggr
net=emi
numPrec=0.25
prec=NH3;NOX;PM10;SO2;VOC
rag=4
and I must read only the values after the =, and with the prec's values, I must separate every single value (delimited with ;) with a new line and then I write those into a new file like:
NH3
NOX
PM10
SO2
VOC
To read after equals symbolt there is no problems, but I can't to separate price.
This is my function:
void settaggiRete(char values[20][50]){
char line[50];
int i = 0, j = 0;
char str[10][20];
FILE *conf = fopen("conf.txt", "r");
if(conf == NULL){
printf("Impossibile apripre il file conf\n");
exit(EXIT_FAILURE);
}
//Ciclo sulle linee del file di configurazione
while(fgets(line, sizeof(line), configRete) != NULL){
// Leggo i valori contenuti dopo =
if(i==10){
char * str = values[10];
sscanf(line, "%*[^=]=%s", values[i]);
while ((token = strsep(line, ";")) != NULL){
str[j] = token;
j++;
}
}else{
sscanf(line, "%*[^=]=%s", values[i]);
}
i++;
}
fclose(configRete);
}
So How can I separate that values??
You can't assign to the array like this
str[j] = token;
try
strcpy(str[j], token);
althought that is dangerous to do, so you could
size_t length = strlen(token);
if (length >= sizeof(str[j]))
length = sizeof(str[j]) - 1;
memcpy(str[j], token, length);
str[j][length] = '\0';
notice that you are writing safe code at the expense of trimming the token, so a better approach is to use dynamic allocation.
You also, redeclared str inside the loop, so delete this line
char * str = values[10];
which is presumably wrong depending on how you declared values.
do separate at main.
like this :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void settaggiRete(char values[20][50]){
char line[50];
int i = 0;
FILE *conf = fopen("conf.txt", "r");
if(conf == NULL){
printf("Impossibile apripre il file conf\n");
exit(EXIT_FAILURE);
}
while(fgets(line, sizeof(line), conf) != NULL){
sscanf(line, "%*[^=]=%49s", values[i++]);
}
fclose(conf);
}
int main(void){
char values[20][50] = {{0}};
char *value11[25];
int i, v11 = 0;
settaggiRete(values);
for(i=0;i<20;i++){
if(!*values[i])
break;
if(i==11){
char *token, *p = values[11];
int j = 0;
while(token = strsep(&p, ";")){
value11[v11++] = token;
}
for(j = 0; j < v11; ++j){
printf("values[11][%d]=%s\n", j, value11[j]);
}
} else {
printf("values[%d]=%s\n", i, values[i]);
}
}
return 0;
}