fscanf not reading from file - c

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

Related

How can i fix this problem of " incompatible types"?

I want to make a program that returns the average of the numbers entered but i get this error:
incompatible types when assigning to type ‘float *’ from type ‘float’
#include <stdio.h>
#include <stdlib.h>
#define CANT ((int)99)
float* promedio (float *dataPtr, int dataCant)
{
float *p;
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
*dataPtr +=1;
}
p = total / dataCant;
return (p);
}
int main (void)
{
float v[CANT],*q;
int i;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) || (v [i] != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &v[i]);
i++;
}
q = promedio (&v[0], i);
printf ("El promedio vale %f\r\n", *q);
free (v);
return (0);
}
Your approach of returning a pointer from promedio doesn't make much sens.
You probably want this:
void promedio (float *dataPtr, int dataCant, float *result)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1; // remove the *, you want to increment the pointer
} // not the thing it points to
*result = total / dataCant;
}
int main (void)
{
float v[CANT],*q;
int i;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) || (v [i] != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &v[i]);
i++;
}
float q;
promedio (&v[0], i); // you should write `v` innstead of the cumbersome `&v[0]`
printf ("El promedio vale %f\r\n", q); // q is a float, removge the *
// remove free (v), you can only free stuff allocated via malloc and friends
return (0);
}
Anyway, I have the strong impression you should read again the chapter dealing with pointers in your learning material.
It turns out you rather need this:
float promedio (float *dataPtr, int dataCant)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1; // remove the *, you want to increment the pointer
} // not the thing it points to
return = total / dataCant;
}
#Jabberwocky
Thank you for your answer, thanks it I managed to solve the exercise. This is the answer (works)
#include <stdio.h>
#include <stdlib.h>
#define CANT ((int)99)
float promedio (float *dataPtr, int dataCant)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1;
}
return (total / dataCant);
}
int main (void)
{
float v[CANT], q, a;
int i=0;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) && (a != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &a);
if (a != -1) {
v[i]=a;
i++;
}
}
q = promedio (&v[0], i);
printf ("El promedio vale %0.2f\r\n", q);
return (0);
}

.exe program crashes when I try to work with a .txt file

I'm trying to read a .txt file. The task is to read temperatures and give out min, max and average values. The txt file is called Temp.txt and it looks like this :
5 76 56 34 35 10
4 45 23 24 14
0
2 32 34
Here is the code that I've written. I have also tried to run it using just the file name like 'fopen("Temp.txt","r")' but I get the same result.
#include<stdio.h>
#include<string.h>
int ReadTempFile(FILE *fp, float temperatur[]);
float maxTemp(int anzahl, float temperatur[]);
float minTemp(int anzahl, float temperatur[]);
float mittlereTemp(int anzahl, float temperatur[]);
float fahrenheit(float celsius);
int ReadTempFile(FILE *fp, float temperatur[]) //For reading individual rows from txt file
{
int i=0;
fscanf(fp,"%f", &temperatur[0]);
for(i = 0; i < temperatur[0]; ++i)
{
fscanf(fp, "%f", &temperatur[i+1]);
}
return temperatur[0];
}
float maxTemp(int anzahl, float temperatur[]) //Maximum Temperature
{
int i = 0;
float max;
max = temperatur[i+1];
for(i = 1; i < anzahl; i++)
{
if(temperatur[i+1] > max)
{
max = temperatur[i+1];
}
}
return max;
}
float minTemp(int anzahl, float temperatur[]) //Minimum Temperature
{
int i = 0;
float min;
min = temperatur[i+1];
for(i = 1; i < anzahl; i++)
{
if(temperatur[i+1] < min)
{
min = temperatur[i+1];
}
}
return min;
}
float mittlereTemp(int anzahl, float temperatur[]) //Average Temperature
{
int i, sum = 0;
float mit;
for (i = 0; i <= anzahl; i++)
{
sum += temperatur[i];
}
mit = sum/temperatur[0];
return mit;
}
float fahrenheit(float celsius) //Celsius to Fahrenheit
{
float f;
f = (celsius*9/5) + 32;
return f;
}
int main()
{
int end, n, Zeile=1;
float temperatur[20], max, min, mit, fmax, fmin, fmit;
char eingabe[20];
FILE *fp=NULL;
do
{
printf("Enter File name: \n"); //Enter file name
fflush(stdout);
scanf("%s", eingabe);
fp = fopen(eingabe, "r" );
if(fp == NULL) printf ("Error: File %s can't be opened!\n", eingabe); //Error message for File cant be opened
}while(fp != NULL);
do{
n = ReadTempFile(fp, temperatur);
max = maxTemp(n, temperatur);
printf("Das Maximum der Zeile %d ist: %.3fC \t",Zeile, max);
fmax = fahrenheit(max);
printf("In Fahrenheit: %.3fF\n", fmax);
min = minTemp(n, temperatur);
printf("Das Minimum der Zeile %d ist: %.3fC \t",Zeile, min);
fmin = fahrenheit(min);
printf("In Fahrenheit: %.3fF\n", fmin);
mit = mittlereTemp(n, temperatur);
printf("Der Mittelwert der Zeile %d ist: %.3fC \t",Zeile, mit);
fmit = fahrenheit(mit);
printf("In Fahrenheit: %.3fF\n", fmit);
++Zeile;
end = feof(fp);
printf("\n\n");
}while (end == 0);
fclose(fp);
return 0;
}
This is what happens after I run the above program.
Thank you in advance.
The most immediate problem that is likely causing the crash is the logic for opening a file:
do
{
printf("Enter File name: \n"); //Enter file name
fflush(stdout);
scanf("%s", eingabe);
fp = fopen(eingabe, "r" );
if(fp == NULL) printf ("Error: File %s can't be opened!\n", eingabe);
}while(fp != NULL); // <- Loops until it fails
This will guarantee that the loop will not end until a file fails to open. When you later try to fscanf from fp set to NULL, you'll have undefined behavior (and this may manifest itself as a crash).
Suggested fix:
for(;;) {
puts("Enter File name:");
if(scanf("%19s", eingabe) == 1) { // make sure scanf succeeds
fp = fopen(eingabe, "r" );
if(fp) break; // break out when it succeeds to open
perror(eingabe);
} else {
fprintf(stderr, "Error: No filename entered.\n");
return 1;
}
}
Note: In your example-run, you showed that you entered Temp to open Temp.txt. You must enter Temp.txt to successfully open Temp.txt.
Here is your program with some other fixes too. I've commented inline so you see why I suggest the changes.
Notes:
I've removed the +1 offset in temperatur completely. You shouldn't use the first float to store the count of temperatures which is an integer value.
Your mittlereTemp didn't use this offset, so it gave the wrong answers too.
mittlereTemp didn't calculate the median temperature (which I think "mittlereTemp" means). It tried to calculate the average temperature, so I changed the name to durchschnittsTemp.
#include <math.h>
#include <stdio.h>
#include <string.h>
// For reading individual rows from txt file
// max_anzahl added to not try to read too many
int ReadTempFile(FILE* fp, float temperatur[], int max_anzahl) {
int count;
// return -1 on failure
if(fscanf(fp, "%d", &count) != 1) return -1;
// we can't read all the entries if count > max_anzahl
if(count > max_anzahl || count < 0) return -1;
for(int i = 0; i < count; ++i) {
if(fscanf(fp, "%f", &temperatur[i]) != 1) {
return -1; // could not read count floats, failure
}
}
return count;
}
// The idiomatic way is to have the array pointer first and
// the count second so I swapped the order of temperatur and anzahl:
float maxTemp(float temperatur[], int anzahl) {
if(anzahl == 0) return NAN; // if we have no values, we have no max temp
float max = temperatur[0];
for(int i = 1; i < anzahl; i++) {
if(temperatur[i] > max) {
max = temperatur[i];
}
}
return max;
}
float minTemp(float temperatur[], int anzahl) {
if(anzahl == 0) return NAN; // if we have no values, we have no min temp
float min = temperatur[0];
for(int i = 1; i < anzahl; i++) {
if(temperatur[i] < min) {
min = temperatur[i];
}
}
return min;
}
// I changed the name to durchschnittsTemp
float durchschnittsTemp(float temperatur[], int anzahl) {
if(anzahl == 0) return NAN; // if we have no values, we have no average temp
float sum = 0.f; // use the proper type for sum
for(int i = 0; i < anzahl; i++) {
sum += temperatur[i];
}
return sum / (float)anzahl;
}
float fahrenheit(float celsius) {
float f;
f = (celsius * 9 / 5) + 32;
return f;
}
// since opening the file is a lot of code, make a function
FILE* open_file_supplied_by_the_user() {
char eingabe[FILENAME_MAX]; // make plenty of room for the filename
for(;;) {
puts("Enter File name:");
// use fgets instead of scanf to make it easier to read filenames with spaces
if(fgets(eingabe, sizeof eingabe, stdin)) {
size_t len = strlen(eingabe);
eingabe[len - 1] = '\0';
FILE* fp = fopen(eingabe, "r");
if(fp) return fp; // break out when it succeeds to open
perror(eingabe); // give the user a proper error message
} else {
fprintf(stderr, "Error: No filename entered.\n");
return NULL;
}
}
}
#define Size(x) (sizeof(x) / sizeof *(x))
int main() {
FILE* fp = open_file_supplied_by_the_user();
if(fp == NULL) return 1; // exit if no file was opened
float temperatur[20];
// loop until ReadTempFile() returns -1 (failure)
for(int n, Zeile = 1;
(n = ReadTempFile(fp, temperatur, Size(temperatur))) != -1;
++Zeile)
{
float max = maxTemp(temperatur, n);
printf("Das Maximum der Zeile %d ist: %.3fC \t", Zeile, max);
printf("In Fahrenheit: %.3fF\n", fahrenheit(max));
float min = minTemp(temperatur, n);
printf("Das Minimum der Zeile %d ist: %.3fC \t", Zeile, min);
printf("In Fahrenheit: %.3fF\n", fahrenheit(min));
float mit = durchschnittsTemp(temperatur, n);
printf("Der Durchschnittswert der Zeile %d ist: %.3fC \t", Zeile, mit);
printf("In Fahrenheit: %.3fF\n", fahrenheit(mit));
printf("\n\n");
}
fclose(fp);
}

Trouble using fscanf with a dynamic array

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

Returning the address of a structure

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.

C - Can't print dynamic array values

For school (yes, school projects) I need to adapt one C program...
I need to make an array with values from a txt file (that I think it was correctly done).
Now I wanted to print the values, and that's the problem! I tried many ways but I'm always seeing memory adress.
Here's the code:
int* init_dados(char *nome,int *m, int *n, int *iter)
{
FILE *f;
int *p, *q;
int i, j,k,contador=0,lixo=0,aux=0,flag=0;
f=fopen(nome, "r");
if(!f)
{
printf("Erro no acesso ao ficheiro dos dados\n");
exit(1);
}
fscanf(f, " %d %d", m,n);
p = malloc(sizeof(int)*(*m)*(*n));
if(!p)
{
printf("Erro na alocacao de memoria\n");
exit(1);
}
q=p;
for (i = 0; i < *m; i++)
{
for (j = 0; j<*n; j++)
{
//se ainda nao leu nada
if (flag == 0)
{
for (contador = 0; contador < *n; contador++)
{
fscanf(f, "%d", &lixo);
}
flag = 1;
break;
}
if (flag == 1)
{
fscanf(f, " %d", &k);
break;
}
for (contador = 0; contador < k; contador++)
{
fscanf(f, " %d", q++);
}
}
}
//PRINTING CODE
for (i = 0; i < *m; i++)
{
printf("\n");
for (j = 0; j < *n; j++)
{
printf("%d ", &q[j]);
q++;
}
}
fclose(f);
return p;
}
Waiting for your thoughts, thanks !
EDIT:
#iharob I've changed this:
for (contador = 0; contador < k; contador++)
{
fscanf(f, " %d", q++);
}
and
for (i = 0; i < *m; i++)
{
printf("\n");
for (j = 0; j < *n; j++)
{
printf("%d ", p[j]);
p++;
}
}
and still not working
EDIT2:
file:
10 10
1 1 1 1 1 1 1 1 1 1
2
1 8
2
5 6
4
1 2 3 4
1
1
4
1 2 5 8
2
6 10
1
9
4
1 2 3 5
1
8
1
7
print of the result so far:
This is wrong
printf("%d ", &q[i]);
change it to p[i] instead of &q[i]
printf("%d ", p[i]);
when you reach printf("%d ", q[i]) q points to the end of the array, so q[0] == q[lengthOfQ] that is past q, you assigned q = p; to keep p pointing to the begining of the array, hence you should use p in printf("%d ", q[i]); instead of q.
I think this code must be what you need
int *init_dados(char *nome,int *m, int *n, int *iter)
{
FILE *f;
int *p, *q;
int i, j, k, contador = 0, lixo = 0, flag = 0;
f = fopen(nome, "r");
if (f == NULL)
{
printf("Erro no acesso ao ficheiro dos dados\n");
exit(1);
}
fscanf(f, " %d %d", m, n);
p = malloc(sizeof(int) * *m * *n);
if (p == NULL)
{
fclose(f);
printf("Erro na alocacao de memoria\n");
exit(1);
}
q = p;
for (i = 0; i < *m; i++)
{
for (j = 0 ; j <* n ; j++)
{
//se ainda nao leu nada
if (flag == 0)
{
for (contador = 0 ; contador < *n ; contador++)
fscanf(f, "%d", &lixo);
printf("----\n");
flag = 1;
break;
}
else if (flag == 1)
{
fscanf(f, " %d", &k);
flag = 2;
break;
}
else if (flag == 2)
{
for (contador = 0 ; contador < k ; contador++)
fscanf(f, " %d", q++);
}
flag = 1;
}
}
}
//PRINTING CODE
for (i = 0; i < *m; i++)
{
for (j = 0; j < *n; j++)
printf("%d ", p[j]);
printf("\n");
}
fclose(f);
return p;
}
this code:
for (contador = 0; contador < k; contador++)
{
fscanf(f, " %d", q++);
}
will never be executed.
It is in a loop code block, where the driving force is 'flag' and flag is only set to 0 and 1, both the 0 case and the 1 case exit the overall 'for' loop.
Have you dumped the resulting 'p' array to assure the values are correct?
When running the program, did you notice that this code is never executed?
this code:
for (i = 0; i < *m; i++)
{
printf("\n");
for (j = 0; j < *n; j++)
{
printf("%d ", p[j]);
p++;
}
}
has the problem that 'p' should not be incremented.
for two reasons:
1) need to keep pointer to malloc'd memory
2) the variable 'j' is indexing off of 'p' so no need to increment 'p'
the following code compiles, but does raise a compiler warning about unused paramter
the code implements the OPs requirements
#include <stdio.h>
#include <stdlib.h>
// the 'iter' parameter is not used, raises compiler warning,
// suggest adding code to use it or remove that parameter
int* init_dados(char *nome,int *m, int *n, int *iter)
{
FILE *f = NULL;
int *p = NULL; // ptr to malloc'd memory
if( NULL == (p = malloc(1) ) )
{ // then, malloc failed
perror( "malloc failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
int *q = p; // steps into malloc'd memory
int j; // group loop index
int k; // group data size
int contador=0; // read loop counter
int lixo=0; // read and discard work area
if(NULL == (f=fopen(nome, "r") ) )
{ // then, fopen failed
perror("fopen failed" );
printf("Erro no acesso ao ficheiro dos dados\n");
exit( EXIT_FAILURE );
}
// implied else, fopen successful
if( 2 != (fscanf(f, " %d %d", m,n) ) )
{ // then, fscanf failed
perror( "fscanf failed for first line of file" );
free(p);
exit( EXIT_FAILURE );
}
// implied else, fscanf for m, n successful
//se ainda nao leu nada
for (contador = 0; contador < *n; contador++)
{
if( 1 != fscanf(f, " %d", &lixo) )
{ // then, fscanf failed for throwaway data
perror("fscanf failed for throwaway data line" );
free(p);
exit( EXIT_FAILURE );
}
// implied else, fscanf successful
} // end for
// for each data group
for (j = 0; j<(*n); j++)
{
if( 1 != fscanf(f, " %d", &k) )
{ // then, fscanf failed
perror( "fscanf failed for count of data in group" );
free(p);
exit( EXIT_FAILURE );
}
// implied else, fscanf successful
// input data from data group, with echo
printf("\nGroup Number: %d with data count: %d\n", j, k);
for (contador = 0; contador < k; contador++, q++)
{
if( 1 != fscanf(f, " %d", q) )
{ // then, fscanf failed
perror( "fscanf failed for data entry in data group" );
free(p);
exit( EXIT_FAILURE );
}
// implied else, fscanf successful
printf("%3d ", *q);
} // end for
} // end for
fclose(f);
return p;
} // end function: init_dados

Resources