Soy try to make a code that take a .txt in imput and create dynamically a list of particle (with the structure particle created in a header file). The problem here is that when I try to printf the values of the list after it's values are implemented with the scanf function, the only thing gcc return is a list of int 0. Do you know what is wrong with my code?
Thank you by advance and sorry for my bad english(I'm French)
int main(int argc, char **argv) {
FILE *p_file = NULL;
p_file = fopen(argv[1], "r");
if (p_file == NULL) {
fprintf(stderr, "Cannot read file %s!\n", argv[1]);
exit(EXIT_FAILURE);
}
int particle_number;
int fscanf_result = fscanf(p_file, "%d\n", &particle_number);
printf("nombre de particules : %d\n", particle_number);
double px;
double py;
double vx;
double vy;
double mass;
double radius;
double color;
int line_nbr = 0;
particle *list_of_particle;
list_of_particle = (particle*)malloc(particle_number * sizeof(particle));
fscanf_result = fscanf(p_file, "%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &px, &py, &vx, &vy, &mass, &radius, &color);
while (fscanf_result != EOF) {
if (fscanf_result != 7) {
printf("Line number %d is not syntactically correct in particles-tests!\n",
line_nbr);
exit(EXIT_FAILURE);
}
particle *p = malloc(sizeof(particle));
(p -> position).x = px;
(p -> position).y = py;
(p -> velocity).x = vx;
(p -> velocity).y = vy;
p -> mass = mass;
p -> radius = radius;
p -> color = color;
printf("couleur du pointeur : %d\n", (p -> color));
list_of_particle[line_nbr] = *p;
line_nbr ++;
printf("vérification de la couleur de la liste : %d\n", (list_of_particle[line_nbr]).color);
printf("valeur du fscanf : %d\n", fscanf_result);
//printf("vérification du rayon de la particule numéro %d : %lf\n", line_nbr, (list_of_particle[line_nbr] -> radius));
fscanf_result = fscanf(p_file, "%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &px, &py, &vx, &vy, &mass, &radius, &color);
free(p);
}
fclose(p_file);
p_file = NULL;
}
Related
I want to use pointer in here, but it's not right.
It has Thread 1: breakpoint 1.1 (1) in
(*(exy + i)) = g;
Please tell me how use the operation of pointer.
#define _CRT_SECURE_NO_WARNINGS
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#include<stdio.h>
#include<stdlib.h>
#define M 3
#define N 3
int readmoduluskai(filename, time, gcoef, kcoef, ge, ke, dm)
char filename[];
char dm[];
double *time, *gcoef, *kcoef;
double *ge, *ke;
{
FILE *fp;
int i = 0;
printf("Modulus file name : ");
scanf("%s", filename);
if (NULL == (fp = fopen(filename, "r"))) {
printf("\7\n Cannot open file..\n\n");
exit(1);
}
//fscanf(fp, "%12lg", &ge);
//fscanf(fp, "%12lg", &ke);
//printf("%12lg %12lg \n", ge, ke);
while (3 == fscanf(fp, "%lg %lg %lg", time, gcoef, kcoef)) {
printf("%12lg %12lg %12lg \n", *(time), *(gcoef), *(kcoef));
time++;
gcoef++;
kcoef++;
i++;
}
//printf("Please enter the constitutive parameters : ");
//scanf("%s", dm);
fclose(fp);
return i;
}
int readdata(file, t, ex, ey, ez, eyz, ezx, exy, ekk)
char *file;
double *t, *ex, *ey, *ez, *eyz, *ezx, *exy, *ekk;
{
double a, b, c, g;
FILE *fp;
int i = 0;
printf("File name : ");
scanf("%s", file);
if (NULL == (fp = fopen(file, "r"))) {
printf("Cannot open file..\n\n");
exit(1);
}
while (4 == fscanf(fp, "%lg %lg %lg %lg", &a, &b, &c, &g)) {
printf("%12lf %12lf %12lf %12lf \n", a, b, c, g);
(*(t + i)) = a;
(*(ex + i)) = b;
(*(ey + i)) = c;
(*(exy + i)) = g;
i++;
}
fclose(fp);
return i;
}
int main(int argc, char *argv[])
{
char filename[20];
char dm[2];
char file[20];
double *time;
double ptime = 0;
time = &ptime;
double *gcoef;
double pgcoef = 0;
gcoef = &pgcoef;
double *kcoef;
double pkcoef = 0;
kcoef = &pkcoef;
double *ge;
double pge = 0;
ge = &pge;
double *ke;
double pke = 0;
ke = &pke;
double *t;
double pt = 0;
t = &pt;
double *ex;
double pex = 0;
ex = &pex;
double *ey;
double pey = 0;
ey = &pey;
double *ez;
double pez = 0;
ez = &pez;
double *eyz;
double peyz = 0;
eyz = &peyz;
double *ezx;
double pezx = 0;
ezx = &pezx;
double *exy;
double pexy = 0;
exy = &pexy;
double *ekk;
double pekk = 0;
ekk = &pekk;
time = (double *)malloc(sizeof(double));
gcoef = (double *)malloc(sizeof(double));
kcoef = (double *)malloc(sizeof(double));
ge = (double *)malloc(sizeof(double));
ke = (double *)malloc(sizeof(double));
readmoduluskai(filename, time, gcoef, kcoef, ge, ke, dm);//read the modulus parameters
readdata(file, t, ex, ey, ez, eyz, ezx, exy, ekk);
free(time);
free(gcoef);
free(kcoef);
free(ge);
free(ke);
return 0;
}
how can I change it
im trying to read some input from my txt file but i dont know why its not reading ...
What am i doing wrong ?
Content of the file :
3 1.0
0.05 0.2 0.5
Function to read :
float * le_dados_ficheiro(char *nomeFich,int *nMoedas, float *valor)
{
FILE *f;
float *p,*q;
int i;
f = fopen(nomeFich,"r");
if(!f)
{
printf("Erro ao abrir ficheiro %s\n",nomeFich);
exit(1);
}
fscanf(f," %d %f",nMoedas,valor);//**It is empty after this**
p = malloc(sizeof(float)*(*nMoedas));
if(!p)
{
printf("Erro ao reservar memoria ... \n");
exit(1);
}
q = p;
for(i = 0; i < *nMoedas; i++)
fscanf(f," %f",q++);
fclose(f);
printf("%f - %f - %f",q[0],q[1],q[2]);//**Still empty**
return q;
}
You are simply printing the wrong data here:
printf("%f - %f - %f", q[0], q[1], q[2]);
q points after the end of your array. You need to print p:
printf("%f - %f - %f", p[0], p[1], p[2]);
Otherwise your program works providing the exact content of your file is this:
3 1.0
0.05 0.2 0.5
Correct code with error checking:
float *le_dados_ficheiro(char *nomeFich, int *nMoedas, float *valor)
{
FILE *f;
float *p, *q;
int i;
f = fopen(nomeFich, "r");
if (!f)
{
printf("Erro ao abrir ficheiro %s\n", nomeFich);
exit(1);
}
if (fscanf(f, " %d %f", nMoedas, valor) != 2)
{
printf("Wrong file format ... \n");
exit(1);
}
p = malloc(sizeof(float)*(*nMoedas));
if (!p)
{
printf("Erro ao reservar memoria ... \n");
exit(1);
}
q = p;
for (i = 0; i < *nMoedas; i++)
{
if (fscanf(f, " %f", q++) != 1)
{
printf("Wrong file format ... \n");
exit(1);
}
}
fclose(f);
printf("%f - %f - %f", p[0], p[1], p[2]);
return q;
}
I need to display a board who have this structure
only with O - | chars
Have this error
main.c:17:29: error: expected primary-expression before ‘]’ token
desplegar_tablero(&tablero[][],fil,col);
(still not complete the algorithm but i'm working in it)
int main(int argc, char **argv){
if (argc != 3){
fprintf(stderr, "Ejecutar como ./prog N_filas N_columnas.\n");
exit(EXIT_FAILURE);
}
int fil = 2*(atoi(argv[1]))-1;
int col = 2*(atoi(argv[2]))-1;
char tablero[fil][col];
desplegar_tablero(&tablero[][],fil,col);
}
void desplegar_tablero(char tab[][], int f, int c){
for (int i = 1; i<= f; ++f){
for (int j = 1; j <=c; ++c){
//Si fila es impar
if (i%2 == 1){
//Columna Impar
if (j%2 == 1){
// ASCII 79 = O
tab[i][j]= 79;
printf(" %u ",&tab[i][j]);
}
//Columna par
else{
// ASCII 196 = -
tab[i][j] = 196;
printf(" %u ",&tab[i][j]);
}
}
// Si fila par
else{
//Columna impar
if (j%2==1){
// ASCII 179 = |
tab[i][j]= 179;
printf(" %u ",&tab[i][j]);
}
//Columna par
else{
// ASCII 32 = espacio
tab[i][j] = 32;
printf(" %u ",&tab[i][j]);
}
}
printf("\n");
}
}
}
This is the code I am working on and in the function trace* readTrace(char* fileName) I have to read a file (that fills structure) and then return the address of trace structure. Also the time and value of the structure are pointers but I don't know how to do it.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#define TMAX 1000
#define NBPTS 2000
#define DT 0.5
typedef struct
{
char comment[40];
int nbpts;
float time[4096];
float value[4096];
} trace;
void simuTrace(int tmax, float dt, float params[], trace *uneTrace)
{
printf("Shkruani emrin e eksperimentit : \n");
scanf("%s", &uneTrace->comment);
int i = 0;
float v = 0, w = 0, dv = 0, dw = 0, t = 0;
float a = params[0], d = params[1], e = params[2];
while (t <= tmax)
{
dv = (a - v) * (v - 1) * v - w;
dw = e * (0.5 * v - w - d);
v += dv * dt;
w += dw * dt;
uneTrace->time[i] = t;
uneTrace->value[i] = v;
i++;
t += dt;
}
uneTrace->nbpts = i;
}
void printTrace(trace uneTrace)
{
printf("%s\n", uneTrace.comment);
printf("\t%d\n", uneTrace.nbpts);
int i;
for (i = 0; i <= NBPTS; i++) {
printf(" t= %.1f \tv= %.4f \n ", uneTrace.time[i],uneTrace.value[i]);
}
}
void saveTraceBin(char *fileTrace, trace uneTrace)
{
FILE *file;
file = fopen(fileTrace, "w");
if (fopen(fileTrace, "w") == NULL) {
printf("\n Gabim! \n");
} else {
fprintf(file, "%s\n", uneTrace.comment);
fprintf(file, "%d", uneTrace.nbpts);
int i;
for (i = 0; i <= NBPTS; i++) {
fprintf(file, "\n %.1f %.4f",uneTrace.time[i],uneTrace.value[i]);
}
fclose(file);
}
}
void readTrace(char *fileName, trace *uneTrace)
{
FILE*file;
file = fopen(fileName, "r");
if (file != NULL) {
fscanf(file, "%s", uneTrace->comment);
fscanf(file, "%d", &uneTrace->nbpts);
int i;
for (i = 0; i <= NBPTS; i++) {
fscanf(file, "%f", &(uneTrace->time[i]));
fscanf(file, "%f", &(uneTrace->value[i]));
}
printf("\n Leximi perfundoi me sukses!\n");
} else {
printf("\n Gabim! \n");
}
fclose(file);
}
trace* readTrace(char* fileName) {
FILE*file;
file = fopen(fileName, "r");
if (file != NULL) {
fscanf(file, "%s", uneTrace->comment);
fscanf(file, "%d", &uneTrace->nbpts);
int i;
for (i = 0; i <= NBPTS; i++) {
fscanf(file, "%f", &(uneTrace->time[i]));
fscanf(file, "%f", &(uneTrace->value[i]));
}
printf("\n Leximi perfundoi me sukses!\n");
} else {
printf("\n Gabim! \n");
}
fclose(file);
}
float errorTrace(trace uneTrace1, trace uneTrace2)
{
float sum = 0;
int i;
for (i = 0; i <= NBPTS; i++)
{
sum += (uneTrace1.value[i] - uneTrace2.value[i]);
}
sum /= NBPTS;
return sqrt(fabs(sum));
}
int main()
{
float Pa[] = { 0.5, 0.01, 0.05 };
float Pb[] = { 0.75, 0.3, 0.1 };
float e1, e2;
trace tracePa, tracePb, traceCell;
simuTrace(NBPTS, DT, Pa, &tracePa);
printTrace(tracePa);
saveTraceBin("myfile1.txt", tracePa);
simuTrace(NBPTS, DT, Pb, &tracePb);
printTrace(tracePb);
saveTraceBin("myfile2.txt", tracePb);
readTrace("cell.txt", &traceCell);
e1 = errorTrace(traceCell, tracePa);
e2 = errorTrace(traceCell, tracePb);
printf("\n Gabimi nga llogaritja e Pa : %f ", e1);
printf("\n Gabimi nga llogaritja e Pb : %f ", e2);
if (e1 < e2)
printf("\n\n Rasti Pa eshte me i mire se rasti Pb \n");
else
printf("\n\n Rasti Pb eshte me i mire se rasti Pa \n");
return 0;
}
You can either return a trace* that is allocated in readTrace,
trace* readTrace(char* fileName) {
trace *tp = malloc(sizeof *tp);
if (!tp) return NULL;
// fill up tp from file
....
}
// call this in main
trace *t = readTrace("cell.txt");
free(t); // free it when done
Or you could supply trace to the function, like
void readTrace(char* filename, trace *tp) {
if (!tp) return;
// fill up tp from file
....
}
// call this in main
trace t; // define trace object
readTrace("cell.txt", &t);
As for fill up time and value, read the array from the file:
int i;
fscanf(file, "%d", &t->nbpts);
for (i = 0; i < t->nbpts; i++) {
fscanf(file, "%f", &(t->time[i]));
fscanf(file, "%f", &(t->value[i]));
}
The function structure should look like this
trace* readTrace(char* fileName)
{
trace* traceptr;
int no_of_elements;
// Read the no of trace elements stored in file
// Generally this is avaliable in a location in the start of file,
// If not, then you have to guess and resize if it falls short.
traceptr = malloc(sizeof(trace) * no_of_elements);
// Read the trace elements from file
return (traceptr);
}
To call it in main()
int main(void)
{
trace *traceptr;
// Other stuff
traceptr = readTrace(filename);
simuTrace(NBPTS, DT, Pa, traceptr);
}
You need to modify your printTrace function to take a pointer to struct as input instead of an entire structure. Then it can take traceptr as it's input. Similarly for the saveTraceBin function.
i'm on a project where i have to make a program that will draw an ASCII from a JPEG.
The program will chose a char according to the HSL value of a pixel : Hue, Saturation, Lightness
So, as a JPEG file is in RGB, i convert it into HSL.
But i find my program pretty slow and it slows my whole virtual machine lel
Do you know how i could improve it for making it a little bit faster ?
it's in my write i call the function that converts RGB into HSL
here it is :
main.c :
#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
#include "fonctions.h"
int main (int argc, char** argv){
int H;
int W;
int C;
FILE *fichier = NULL; //file pour l'image entrée
FILE *image = NULL; //file pou l'image à la sortie
unsigned char **buffer; //buffer où sera contenue l'image
buffer = malloc(256*(sizeof(unsigned char*)));
if (argv[1] == NULL)
fichier = fopen("cara.jpg", "r");
else
fichier = fopen(argv[1], "r");
image = fopen("cara_image_cree.jpg", "wb");
if (fichier == NULL)
printf("Probleme lecture");
printf("Cara Delevingne\n");
buffer = lire(fichier, &H, &W, &C);
/* afficher 3 sous-pixels :
printf("\nBuffer case 1 : %d", buffer[0][0]);
printf("\nBuffer case 1 : %d", buffer[0][0+1]);
printf("\nBuffer case 1 : %d\n", buffer[0][0+2]);*/
ecrire(&H, &W, &C, buffer, image);
fclose(fichier);
fclose(image);
return 0;
}
read.c :
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <jpeglib.h>
#include <jerror.h>
unsigned char** lire (FILE* file, int *H, int *W, int *C){
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
int n = 0;
unsigned char** buffer; // buffer qui va contenir l'image
/*printf("SHITSHITSHITSHITDEBUG\n");
fflush(stdout);*/
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo); // Initialisation de la structure
jpeg_stdio_src(&cinfo,file); // file est de type FILE * (descripteur de fichier
// sur le fichier jpega decompresser)
jpeg_read_header(&cinfo,TRUE);// lecture des infos sur l'image jpeg
jpeg_start_decompress(&cinfo);// lancement du processus de decompression
*H = cinfo.output_height; // on récupère la hauteur
*W = cinfo.output_width; // on récupère la largeur
*C = cinfo.output_components; // on regarde si l'image est en couleurs ou N&B
buffer=malloc( (*H) *sizeof(unsigned char*) ); // on alloue de la mémoire au buffer selon le nb de lignes de pixels qu'il va devoir prendre
while (n < *H) // tant que le compteur n'a pas dépassé l'image
{
buffer[n] = (unsigned char*) malloc( (*W) * (*C) *sizeof(unsigned char *) ); // on alloue à chaque ligne, la taille de la largeur
jpeg_read_scanlines(&cinfo,buffer+n,1); // lecture des n lignes suivantes de l'image
// dans le buffer (de type unsigned char *)
n++;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return buffer;
}
write.c :
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <jpeglib.h>
#include <jerror.h>
void ecrire (int *H, int *W, int *C, unsigned char **buffer, FILE *file){
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
float** bufferHSL;
int n = 0; // parcoureurs pour écrire l'image
int i = 0; // parcoureurs pour transformer en HSL
int j = 0;
float h = 0; // variables pour stocker le résultat HSL
float s = 0;
float l = 0;
int r, g, b;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo); // Initialisation de la structure
jpeg_stdio_dest(&cinfo,file); // file est de type FILE * (descripteur de fichier
// sur le fichier jpeg compressé final)
cinfo.image_width= *W; // nombre de ligne de l'image
cinfo.image_height= *H; // nombre de pixel par ligne
cinfo.input_components = *C; // 3 pour une image couleur, 1 pour une N&B
cinfo.in_color_space= JCS_RGB;
// JCS_GRAYSCALE pour une image N&B
jpeg_set_defaults(&cinfo); // initialisation des paramètres de compression
jpeg_start_compress(&cinfo,TRUE); // lancement du processus de decompression
bufferHSL = (float **) malloc( (*H) *sizeof(long int*) );
while (i < *H){ // lecture des lignes pour transformation HSL
j = 0;
while (j < *W){
/*printf("i : %d /t j : %d \n",i , j);
fflush(stdout);*/
bufferHSL[i] = (float*)malloc( (*W) *sizeof(long int*) );
r = buffer[i][j];
g = buffer[i][j+1];
b = buffer[i][j+2];
rgbToHsl(r, g, b, &h, &s, &l);
bufferHSL[i][j] = h;
bufferHSL[i][j+1] = s;
bufferHSL[i][j+2] = l;
j++;
/*printf("TESTTEST\n");
fflush(stdout);*/
}
i++;
}
while (n < *H)
{
jpeg_write_scanlines(&cinfo,buffer+n,1);// écriture des n lignes suivantes de l'image
// stockées dans le buffer (de type unsigned char *)
n++;
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
}
RGB_to_HSL.c :
void rgbToHsl(int r, int g, int b, int *h, int *s, int *l){
r/=255; g /= 255; b/=255;
int max = maximum(r, g, b);
int min = minimum(r, g, b);
*l = (max + min)/2;
if (max == min)
*h = *s = 0; // achromatique
else{
int d = max - min;
*s = *l > 0.5 ? d / (2 - max - min) : d / (max + min);
if (max == r)
*h = (g-b) / d + (g < b ? 6 : 0);
if (max == g)
*h = (b-r) / d + 2;
if (max == b)
*h = (r-g) / d + 4;
/*case r: *h = r;
case g: *h = g;
case b: *h = b; */
}
*h /= 6;
}
int maximum (int a, int b, int c){
if (a > b){
if (a > c)
return a;
else
return c;
}
else{
if (b > c)
return b;
if (c > b)
return c;
}
}
int minimum (int a, int b, int c){
if (a < b){
if (a < c)
return a;
else
return c;
}
else{
if (b < c)
return b;
if (c < b)
return c;
}
}
You should run some profiling tool to see exactly which parts take how long to execute and optimize that.
Without that, a quick look shows you are calling malloc a lot in an inner loop, here:
bufferHSL = (float **) malloc( (*H) *sizeof(long int*) );
while (i < *H){ // lecture des lignes pour transformation HSL
j = 0;
while (j < *W){
bufferHSL[i] = (float*)malloc( (*W) *sizeof(long int*) );
Actually, that seems just wrong - You are calling it for every j < *W iteration, but you only need it once per i. You are leaking the allocation, and only doing anything on it in the last iteration - are you sure your output is correct?
As a first step, I recommend moving that line out of the inner while loop.
There is room for several other microoptimizations, but I don't think you need to do them. Just make sure the code is first correct, and then find the part that is slow (usually it is the innermost loop), and focus just on that.