C program crash inverse file txt - c

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

Related

How to initialize a 2D grid from a file for a Game Of Life in C?

For a school project, I am trying to build a Game Of Life in C to play with in the terminal.
The program should do the following sequence of actions:
Take a file, open it and get the dimensions (working)
Initialize a grid corresponding to the file that looks good (wip - help)
display that grid (should work)
compute all next generation (wip) and print them too
So far, with my teammate, we built some helper functions to parse the file and get the dimensions of the grid we need to allocate for the game to work, print the function, do the necessary stuff in order to compute the next generation... However I can't seem to get my function to initialize my grid by mapping characters in the file to characters in the terminal.
Can anyone help me ? We are trying to do it the easy way since we have not really seen any advanced concepts, so the solution must not use any advanced concepts too... If someone finds something, it would really help us a lot!
Here is the code with the relevant parts (everything else should not interfere, and sorry if the comments are in French) (if anyone wants the full code, I'll post it):
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define INVALID_CHAR_READING 101
#define CANT_OPEN_FILE 201
#define FAIL_UPDATE 102
/// #brief Obtient les dimensions de la grille du jeu de la vie
/// #param filename le nom du fichier
/// #param dimensions un tableau de dimensions non instancié
/// #return un tableau d'entier contenant dans l'ordre lignes, colonnes
void get_dimensions(char filename[], int *dimensions)
{
errno = 0;
FILE *content = fopen(filename, "r");
if (content == NULL)
{
fprintf(stderr, "Une erreur s'est produite a l'ouverture du fichier %s : %s\n", filename, strerror(errno));
exit(CANT_OPEN_FILE);
}
int lines = 0;
int columns = 0;
char buffer;
for (buffer = getc(content); buffer != EOF; buffer = getc(content))
{
if (buffer == '\n')
{
lines = lines + 1;
}
columns += 1;
}
columns /= lines;
// columns /= 2; // on a compté les espaces
fclose(content);
dimensions[0] = lines;
dimensions[1] = columns;
}
void init_grid(char filename[], char **grid, int *dimensions)
{
errno = 0;
FILE *content = fopen(filename, "r");
if (content == NULL)
{
fprintf(stderr, "Une erreur s'est produite a l'ouverture du fichier %s : %s\n", filename, strerror(errno));
exit(CANT_OPEN_FILE);
}
int line = 0;
int column = 0;
char ch;
while ((ch = fgetc(content)) != EOF)
{
while (column < dimensions[1] && line < dimensions[0])
{
switch (ch)
{
case 'o':
grid[line][column] = ' ';
case 'x':
grid[line][column] = ' ';
case '\n':
grid[line][column] = ch;
default:
fprintf(stderr, "Une erreur s'est produite lors de la lecture du caractère à l'initialisation de la grille :/ Votre fichier est peut-être incompatible avec le parseur...\n");
exit(INVALID_CHAR_READING);
}
column++;
};
line++;
}
}
void print_grid(char **grid, int *dimensions)
{
for (int i = 0; i < dimensions[0]; i++)
{
for (int j = 0; j < dimensions[1]; j++)
{
printf("%c", grid[i][j]);
}
};
}
void gol()
{
char filename[256];
printf("Quel est le nom du fichier que vous cherchez à ouvrir ? (Merci d'entrer le chemin complet du fichier)\n> ");
scanf("%s", &filename);
// printf("%s", filename);
int dimensions[2];
get_dimensions(filename, dimensions);
printf("%d %d\n", dimensions[0], dimensions[1]);
char grid[dimensions[1]][dimensions[0]];
// printf("%d", sizeof(grid));
init_grid(filename, &grid, dimensions);
print_grid(grid, dimensions);
}
int main()
{
printf("GOL\n===\nQue voulez-vous faire ? (h: aide, f: chemin de fichier, r: random)\n> ");
char option;
scanf("%c", &option);
switch (option)
{
case 'h':
help();
break;
case 'f':
gol(); // Nécéssaire sinon bypass du contrôle d'initialisation??
break;
case 'r':
// TODO implémentation de la grille random
break;
default:
printf("\nVous n'avez pas rentré d'option valable :( Merci de relancer le programme pour recommencer ;)\n\n");
exit(INVALID_CHAR_READING);
}
return 0;
}
I would recommend not using the multi-dimensional array, but instead do something like:
char grid[ dimensions[1] * dimensions[0] ];
and:
void
init_grid(const char *filename, char *grid, int *dimensions)
{
errno = 0;
FILE *content = fopen(filename, "r");
if( content == NULL ){
fprintf(stderr, "Une erreur s'est produite a l'ouverture du fichier %s : %s\n", filename, strerror(errno));
exit(CANT_OPEN_FILE);
}
int ch;
char *end = grid + dimensions[0] * dimensions[1];
while ((ch = fgetc(content)) != EOF && grid < end ){
*grid++ = ch == '\n' ? '\n' : ' ';
}
if( fclose(content) ){
perror(filename);
}
}
If you do want to keep the multi-dimensional array, you can do things like:
char grid[dimensions[1]][dimensions[0]];
char *g = &grid[0][0];
and then pass g to helper functions. Be aware of any compiler warnings you get about mismatched types in parameters.

Reading from binary file LANG C

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
}
}
}
}
}
}

C Program don't have the same result when compiled on linux and windows

When I compile my program with mingw on windows and gcc on linux, the executable file doesn't give me the same result.
This code is supposed to take a file and encrypt it.
But when I need to add some bytes if the last block is not full or if the file is less than 32 bytes, Linux adds the value "0" like I want but on Windows, it doesn't work.
By the way, the hexdump of each isn't similar.
to execute it : ./encrypt [FileIn] [FileOut] 1 [yourKey] [yourIV]
Put anything you want for Key and IV, they are written inside the code for the test(I just put "1" and "1" to don't get an error)
argv[3] needs to be a "1" to encrypt
I'm testing it using a file with "toto" written inside (put anything you want, but be under 32 char because it's what i'm testing for now).
Key and IV are same inside the code to debug, it's not a mistake.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*FUNCTIONS*/
int encrypt(char* in, char* out, char* key, char* primalIv);
int decrypt(char* in, char* out);
void myprint(char* content, int size);
char* xor(char* data, char* key, int size);
void bitStuffing(char* in, int rem);
/*GLOBAL VARIABLES*/
int errorLevel;
int blockSize = 32; /*Tailles de blocs en octet*/
/*CALL : ./main inFile outFile methode key iv*/
/*FILE STRUC : [datas] [stuffing] [stuffingValue] [iv]*/
int main(int argc, char** argv)
{
/*Support de l'aide à l'utilisateur*/
if(argc == 2 && !strcmp(argv[1],"help"))
{
printf("\nUsage : ./cied [inFile] [outFile] [methode] [key] [iv]\n\n");
printf("[inFile] : Input file to use\n");
printf("[outFile] : Ouput file to use\n");
printf("[methode] : Encrypt (1) or decrypt (0)\n");
printf("[key] : The key to use\n");
printf("[iv] : The initialisation vector.\n");
printf(" (none for decrypt !)\n");
return 0; /*Fermeture gratieuse du programme*/
}
/*Support des erreurs d'arguments*/
if(argc != 5 && argc != 6)
{
printf("[ERR] Args error!\n");
printf("[INF] Enter 'help' to display help\n");
return 1;
}
else if(atoi(argv[3]) == 1 && argc != 6) /*Nombre d'arguments pour chiffrement*/
{
printf("[ERR] Args error : given %d when waiting 5!\n",(argc-1));
printf("[INF] Enter 'help' to display help\n");
return 1;
}
else if(atoi(argv[3]) == 0 && argc != 5)/*Nombre d'arguments pour dechiffrement*/
{
printf("[ERR] Args error : given %d when waiting 4!\n",(argc-1));
printf("[INF] Enter 'help' to display help\n");
return 1;
}
/***Chiffrement et dechiffremet***/
if(atoi(argv[3]) == 1)
{
errorLevel = encrypt(argv[1], argv[2],"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");/*Chiffrement*/
if(!errorLevel)
{
printf("[INF] finished\n");
}
else
{
printf("[ERR] An error as occured.\n");
}
}
else if(atoi(argv[3]) == 0)
{
errorLevel = decrypt(argv[1], argv[2]); /*Dechiffrement*/
if(!errorLevel)
{
printf("[INF] finished\n");
}
else
{
printf("[ERR] An error as occured.\n");
}
}
else
{
printf("[ERR] Wrong method given!");
printf("[INF] Enter 'help' to display help\n");
return 1;
}
return 0;
}
/*FONCTIONS CORE*/
int encrypt(char* in, char* out, char* key, char* primalIv)
{
/*Variables*/
char* block = NULL;
char* xored = NULL;
char* iv = NULL;
int readed;
int inFileSize;
int numOfBlock;
int rem = 0;
int i;
FILE *inFile;
FILE *outFile;
iv = primalIv;
/*Ouverture des fichiers*/
inFile = fopen(in,"rb");
outFile = fopen(out,"w");
/*Gestion des erreurs de fichier*/
if(inFile == NULL)
{
printf("[ERR] Problem reading input file. Please check path and permissions.\n");
}
else if(outFile == NULL)
{
printf("[ERR] Problem reading output file. Please check path and permissions.\n");
}
block = malloc(blockSize);
/*Récupération de la longueur du fichier*/
fseek(inFile, 0, SEEK_END);
inFileSize = ftell(inFile);
rewind(inFile);
/*Calcul du nombre de bloc et du reste*/
numOfBlock = inFileSize / blockSize;
rem = inFileSize % blockSize;
printf("[INF] File will be split in %d block(s). %d will remain.\n",numOfBlock,rem);
if(inFileSize < blockSize)
{
readed = fread(block,1,blockSize,inFile);
printf("[INF] readed %d bytes \n",readed);
/*Bourrage*/
bitStuffing(block,(blockSize-readed));
/*Xor avec l'IV*/
xored = xor(block,iv,blockSize);
/*Xor avec la clé*/
xored = xor(xored,key,blockSize);
/*Sauvegarde du block pour réutilisation en tant qu'IV*/
iv = xored;
/*Ecriture dans le fichier*/
fwrite(xored,1,blockSize,outFile);
}
else
{
for(i=0;i<numOfBlock;i++)
{
printf("qzekonfk le\n");
readed = fread(block,1,blockSize,inFile);
printf("[INF] readed %d bytes \n",readed);
if(readed != blockSize)
{
printf("[WRN] The readed block siez is different than usual !(%d != %d)\n",blockSize,readed);
}
/*Xor avec l'IV*/
printf("IV :\n");
xored = xor(block,iv,readed);
/*Xor avec la clé*/
printf("KEY :\n");
xored = xor(xored,key,readed);
/*Sauvegarde du block pour réutilisation en tant qu'IV*/
iv = xored;
/*Ecriture dans le fichier*/
fwrite(xored,1,readed,outFile);
}
/*Bourrage*/
if(rem)
{
readed = fread(block,1,blockSize,inFile);
printf("[INF] readed %d bytes \n",readed);
/*Bourrage*/
bitStuffing(block,(blockSize-readed));
/*Xor avec l'IV*/
xored = xor(block,iv,readed);
/*Xor avec la clé*/
xored = xor(xored,key,readed);
/*Sauvegarde du block pour réutilisation en tant qu'IV*/
iv = xored;
/*Ecriture dans le fichier*/
fwrite(xored,1,readed,outFile);
}
}
/*Inscription de rem dans le fichier pour préparer le déchiffrement*/
fprintf(outFile, "%c",rem);
/*Inscription de l'IV*/
printf("IV (again):\n");
fwrite(xor(primalIv,key,blockSize),1,blockSize,outFile);
/*Free des malloc*/
free(block);
free(xored);
return 0;
}
int decrypt(char* in, char* out)
{
return 0;
}
/*FONCTIONS UTILITAIRES*/
char* xor(char* data, char* key, int size)
{
int i;
char* result = malloc(size);
for(i=0; i<size; i++)
{
result[i] = data[i] ^ key[i];
printf(" %x ^ %x = %x\n",data[i],key[i],result[i]);
}
return result;
}
void myprint(char* content, int size)
{
int i;
printf(" ");
for(i=0;i<=blockSize;i++)
{
printf(" %x",content[i]);
}
printf("\n");
}
void bitStuffing(char* in, int rem) {
int i;
printf("\nBEGIN STUFFING");
for(i=rem; i<sizeBlock; i++) {
in[i] = 0;
/*printf("%x", in[i]);*/
}
printf("\nEND STUFFING\n");
}
#alk You're true, i found it just before reading your post.
My friend give a wrong value to the bitStuffing() function. He don't need to give the number of empty bytes, but the byte where the loop have to begin. Then it will be
bitStuffing(block, readed);
and not
bitStuffing(block, (blockSize-readed));
For everyone who want a little less code, i create this to have essentially the stuffing :
#include <stdio.h>
#include <stdlib.h>
void bitStuffing(char* in, int rem);
void myprint(char* content, int size);
int blockSize = 32;
int main()
{
char* block;
int inFileSize = 4; /*In my example, the file used is a text file containing "toto"*/
int readed;
FILE *outFile;
readed = inFileSize % blockSize; /*Getting the number of bits to stuff*/
block = malloc(blockSize);
block[0] = "t";
block[1] = "o";
block[2] = "t";
block[3] = "o";
bitStuffing(block, readed);
outFile = fopen("C:/Users/Julien/Desktop/text3.txt", "wb");
fwrite(block,1,blockSize,outFile);
fclose(outFile);
return 0;
}
void bitStuffing(char* in, int begin) {
printf("\nBEGIN STUFFING");
printf("\nrem =%2d", begin);
int i;
for(i=begin; i<blockSize; i++) {
in[i] = 0;
printf("\ni =%1d | value =%1x\n ",i, in[i]);
myprint(in, i);
}
printf("\nEND STUFFING\n");
}
void myprint(char* content, int size)
{
int i;
printf("\n");
for(i=0;i<size;i++)
{
printf("%2x",content[i]);
}
printf("\n");
}
This works as well like i want. Then i was sure that the problem didn't come from the bitStuffing
Thank's everybody
Now, i will slap my friend

fprintf in File not found

I have a problem in the fprintf in the function "menor" because the data is not visible in the file selected, i dont know what is the problem, please help, i think is the reference file, but not idea.
I have a problem in the fprintf in the function "menor" because the data is not visible in the file selected, i dont know what is the problem, please help, i think is the reference file, but not idea
#include < stdio.h >
#include < stdlib.h >
#include < string.h >
typedef struct {
char * nombre;
char * editorial;
int valor;
int area;
int vendido;
}
Libro;
int conteo(FILE * _entrada);
void datos(FILE * _entrada, Libro * _trabajo, int cantidad);
void menor(FILE * _entrada, FILE * _salida, Libro * _trabajo, int cantidad);
int main() {
FILE * entrada;
char ingreso[256];
printf("Direccion del archivo de entrada \n");
scanf("%255s", ingreso);
entrada = fopen(ingreso, "r");
if (entrada == NULL) {
printf("No se pudo acceder al archivo de entrada \n");
exit(1);
}
FILE * salida;
char final[256];
printf("Direccion del archivo de salida \n");
scanf("%255s", final);
salida = fopen(final, "r");
if (salida == NULL) {
printf("No se pudo acceder al archivo de salida \n");
exit(1);
}
int cantidad = conteo(entrada);
Libro * trabajo;
trabajo = (Libro * ) malloc(sizeof(Libro) * cantidad);
datos(entrada, trabajo, cantidad);
menor(entrada, salida, trabajo, cantidad);
return 0;
}
int conteo(FILE * _entrada) {
char auxiliar1[100];
int conteo = 0;
while (!feof(_entrada)) {
fgets(auxiliar1, 100, _entrada);
conteo++;
}
rewind(_entrada);
return (conteo / 5);
}
void datos(FILE * _entrada, Libro * _trabajo, int cantidad) {
char auxiliar2[100];
char * token;
while (!feof(_entrada)) {
fgets(auxiliar2, 100, _entrada);
token = strtok(auxiliar2, ":");
token = strtok(NULL, ":");
(_trabajo - > nombre) = strdup(strtok(token, "\n"));
fgets(auxiliar2, 100, _entrada);
token = strtok(auxiliar2, ":");
token = strtok(NULL, ":");
(_trabajo - > editorial) = strdup(strtok(token, "\n"));
fgets(auxiliar2, 100, _entrada);
token = strtok(auxiliar2, ":");
(_trabajo - > valor) = atoi(strtok(NULL, ":"));
fgets(auxiliar2, 100, _entrada);
token = strtok(auxiliar2, ":");
(_trabajo - > area) = atoi(strtok(NULL, ":"));
fgets(auxiliar2, 100, _entrada);
token = strtok(auxiliar2, ":");
(_trabajo - > vendido) = atoi(strtok(NULL, ":"));
}
}
void menor(FILE * _entrada, FILE * _salida, Libro * _trabajo, int cantidad) {
int i;
int menor = 0;
int posicion = 0;
for (i = 0; i < cantidad; i++) {
if ((_trabajo - > area) == 1) {
menor = (_trabajo - > vendido);
_trabajo++;
}
}
_trabajo--;
fprintf(_salida, "%s", (_trabajo - > nombre));
}
In main, change:
salida = fopen(final, "r");
Into:
salida = fopen(final, "w");
This will truncate the file. If you wanted to update the file (meaning change the existing file's contents without deleting it), you'd want "r+".
Your description of the problem is vague. Please update your question to show us the exact (copy-and-pasted) error message.
But when I compile your program, I get:
c.c:1:26: fatal error: stdio.h : No such file or directory
#include < stdio.h >
^
compilation terminated.
Remove the spaces from the #include directives. Change this:
#include < stdio.h >
#include < stdlib.h >
#include < string.h >
to this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
(The interpretation of the name between < and > is compiler-specific, but in this case the compiler is probably looking for a file whose name is literally " stdio.h ", including the leading and trailing spaces.)

memory in c programming

Hi i try to read a tkt input file to use it in my structure and it works fine but when i try to read the value image or adresse or nom it's empty
someone have any idea?
this is the code :
int nombre_radio(char* fichier_radio)
{
FILE* fichier = NULL;
char buf[TAILLE_MAX_RADIO]="";
int i;
fichier = fopen(fichier_radio, "r");
if (fichier != NULL)
{
i=0;
while (fgets(buf, TAILLE_MAX_RADIO, fichier) != NULL)
{
i++;
}
}
fclose(fichier);
return(i);
}
/* fonction pour récuperer l'image*/
void get_radio(int numero, char* fichier_radio, char* nom, char* adresse, char* image)
{
FILE* fichier = NULL;
char chaine[TAILLE_MAX_RADIO];
int i;
char im_temp[102400];
fichier = fopen(fichier_radio, "r");
if (fichier != NULL)
{
i=0;
while (fgets(chaine, TAILLE_MAX_RADIO, fichier) != NULL && i<numero){i++;}
strcpy(nom, strtok(chaine, "\t"));
strcpy(adresse, strtok(NULL, "\t"));
strcpy(im_temp, strtok(NULL, "\t"));
if (strstr(im_temp, "\n") != NULL)
strncpy(image, im_temp, strlen(im_temp)-1);
else
strncpy(image, im_temp, strlen(im_temp));
}
fclose(fichier);
return;
}
this is the two function to read txt file and to use it to extract image adresse and nom
and i use the functions here:
int i;
char fichier_radio[1024];
strcpy(fichier_radio,"liste_radio.txt");
int nombre_Radio = nombre_radio(fichier_radio);
recording_asset *assets = malloc(sizeof(recording_asset) * 5000);
printf("nombre %d",nombre_Radio);
char *adresse = malloc (sizeof (*adresse) * 256);
char *nom = malloc (sizeof (*nom) * 256);
char *image = malloc (sizeof (*image) * 256);
for(i=0; i<nombre_Radio; i++){
get_radio(i, fichier_radio, nom, adresse, image);
printf("image : ",image[i]);
}
Could you check fclose(fichier);:
If fichier is a null pointer, fclose should not be called. It results in a undefined behavior, hence might explain the crash you are observing.
You should put fclose(fichier); inside your if (fichier != NULL) check condition.
In nombre_radio, please initialize i to a proper value, you will return garbage value if fichier is NULL.

Resources