I have two files, both with 47k lines. I'm trying to read each file's line at the same time. The problem is that only the first line of each file is read. That's the code i wrote:
id_region = fopen(argv[3], "r");
prediction=fopen(argv[4], "r");
int prediction_class, class, region;
while ((fscanf(id_region,"%d 1:%d",&class,®ion) == 2) && (fscanf(prediction,"%d",&prediction_class) == 1))
{
fprintf(stderr,"\nRegião %d",region);
fprintf(stderr,"\nClasse %d",class);
fprintf(stderr,"\nPredição %d",prediction);
}
what's the problem with my code?
EDIT: I tried this code, but i have a segmentation fault when I run it. What's wrong here?
int main(int argc, char** argv)
{
FILE* id_region;
FILE* prediction;
id_region = fopen(argv[1], "r");
prediction=fopen(argv[2], "r");
char line[50];
char line2[50];
int prediction_class,region,temp1,temp2;
while((fgets (line,10,prediction) != NULL) && (fgets (line2, 10, id_region)!=NULL))
{
//formating the input
temp1=fscanf(line,"%d",&prediction_class);
temp2=fscanf(line2,"%d",®ion);
fprintf(stderr,"\nRegion: %d",region);
fprintf(stderr,"\nPrediction: %d",prediction_class);
}
fclose(prediction);
fflush(prediction);
fclose(id_region);
fflush(id_region);
return(0);
}
SOLVED BY THIS CODE- THANKS!
int main(int argc, char** argv)
{
FILE* id_region;
FILE* prediction;
id_region = fopen(argv[1], "r");
prediction=fopen(argv[2], "r");
char line[50];
char line2[50];
int prediction_class,region,class;
contador=0;
while((fgets(line,10,prediction)!= NULL) && (fgets(line2, 20, id_region)!=NULL))
{
sscanf (line,"%d", &prediction_class);
sscanf (line2,"%d 1:%d",&class,®ion);
fprintf(stderr,"\nRegion: %d",region);
fprintf(stderr,"\nPrediction: %d",prediction_class);
}
fclose(prediction);
fflush(prediction);
fclose(id_region);
fflush(id_region);
return(0);
}
Instead of fscanf(), you should use fgets() to get each line, and use sscanf() to get formatted input from the lines.
For the edited question, I spotted at least two problems: you are still using fscanf(), while it should be sscanf(). And you are using fflush() after closing the streams with fclose(). Actually fclose() will cause the streams to flush, you don't need to flush them manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With