I have a code that reads two .txt files and puts them into structs. Then, I want to compare the x value from each file and find matches. The type of these values is floats. I keep getting incorrect matches and line numbers and I'm not sure what to do. It works for the first few but then it just says there's a match when it is only a value in one file. Everything else works fine, so if anyone has suggestions on comparing the values that would be much appreciated. Thank you.
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#define FLT_EPSILON 1.19209290E-07F
typedef struct fcat_s {
float x;
float y;
float a_j2000;
float b_j2000;
float mag;
} fcat_s;
typedef struct cat_s {
float num;
float x;
float y;
float xworld;
float yworld;
float flux_auto;
float mag_auto;
float awin;
float bwin;
} cat_s;
int main(void) {
float exptime = 0;
float F = 0;
float Mi = 0;
float Mcat = 0;
float FLUX_AUTO = 0;
float ZP = 0;
char fcatname[50];
char catname[50];
int fcatcount = 0;
int catcount = 0;
char fcat_c;
char cat_c;
float x;
char str[100];
int i = 0;
int j = 0;
float temp;
int match = 0;
printf("Please input the .fcat file name:\n");
scanf("%str", fcatname);
printf("Please input the .cat file name:\n");
scanf("%str", catname);
printf("Please input the exposure time:\n");
scanf("%f", &exptime);
fcat_s *f = (fcat_s *)malloc(sizeof(fcat_s));
cat_s *c = (cat_s *)malloc(sizeof(cat_s));
// .fcat file
FILE *fcat;
fcat = fopen(fcatname, "r");
if (fcat == NULL) {
printf("The input file does not exist\n");
} else {
for (fcat_c = getc(fcat); fcat_c != EOF; fcat_c = getc(fcat)) {
if (fcat_c == '\n')
fcatcount++;
if (fcatcount > 4) {
fscanf(fcat, "%f", &f[fcatcount-5].x);
fscanf(fcat, "%f", &f[fcatcount-5].y);
fscanf(fcat, "%f", &f[fcatcount-5].a_j2000);
fscanf(fcat, "%f", &f[fcatcount-5].b_j2000);
fscanf(fcat, "%f", &f[fcatcount-5].mag);
}
}
}
printf("\n");
printf("The .fcat file has %d lines. \n", fcatcount);
printf("\n");
printf("\n");
printf("FCAT CONTENTS\n");
for (i = 0; i < (fcatcount-5); i++) {
printf("%lf\t %lf\t %lf\t %lf\t %lf\n",
f[i].x, f[i].y, f[i].a_j2000, f[i].b_j2000, f[i].mag);
}
printf("\n");
printf("\n");
// .cat file
FILE *cat;
cat = fopen(catname, "r");
if (cat == NULL) {
printf("The input file does not exist\n");
} else {
for (cat_c = getc(cat); cat_c != EOF; cat_c = getc(cat)) {
if (cat_c == '\n')
catcount++;
if (catcount > 8) {
fscanf(cat, "%f", &c[catcount-9].num);
fscanf(cat, "%f", &c[catcount-9].x);
fscanf(cat, "%f", &c[catcount-9].y);
fscanf(cat, "%f", &c[catcount-9].xworld);
fscanf(cat, "%f", &c[catcount-9].yworld);
fscanf(cat, "%f", &c[catcount-9].flux_auto);
fscanf(cat, "%f", &c[catcount-9].mag_auto);
fscanf(cat, "%f", &c[catcount-9].awin);
fscanf(cat, "%f", &c[catcount-9].bwin);
}
}
}
printf("\n");
printf("The .cat file has %d lines. \n", catcount);
printf("\n");
printf("\n");
printf("CAT CONTENTS\n");
for (i = 0; (i < catcount-9); i++) {
printf("%lf\t %lf\t %lf\t %lf\t %lf\t %lf\t %lf\t %lf\t %lf\n",
c[i].num, c[i].x, c[i].y, c[i].xworld, c[i].yworld,
c[i].flux_auto, c[i].mag_auto, c[i].awin, c[i].bwin);
}
printf("\n");
printf("\n");
// searching in the files for a match
for (i = 0; (i <= (fcatcount-5)); i++){
for (j = 0; (j <= (catcount-9)); j++) {
if (fabs(f[i].x - c[j].x) < FLT_EPSILON && fabs(f[i].y - c[j].y) < FLT_EPSILON) {
printf("%f\t .fcat line: %d\t .cat line: %d\n", c[j].x, i, j);
match++;
}
}
}
printf("\n");
printf("\n");
printf("The files have %d matches. \n", match);
fclose(fcat);
fclose(cat);
free(f);
free(c);
return 0;
}
You only allocated space for one fcat_s:
fcat_s *f = (fcat_s*)malloc(sizeof(fcat_s));
But in your first loop, you are already treating f like an array:
...
fscanf(fcat, "%f", &f[fcatcount-5].x);
...
Unless I am missing something, it seems that you are reading and writing to unallocated memory. I am surprised your program doesn't segfault.
Related
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);
}
I have the following code for reading files in C. It's reading from files but not like its supposed to be. It is showing up like this:
instead of like this:
Although I am calling the same print function. We are taking records for 4 employees. I know it's a logical error but I am unable to solve it.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct employee {
float hoursWorked, hourlyRate, federalTax, stateTax;
char name[20];
};
struct calc
{
float grosspay, fto, sto, np;
};
void print(struct employee s[], struct calc c[], int n)
{
for (int i = 0; i < 4; i++)
{
printf("\n%s's gross pay: $%.02f\n", s[i].name, c[i].grosspay);
printf("Federal tax owed: $%.02f\n", c[i].fto);
printf("State tax owed: $%.02f\n", c[i].sto);
printf("Net pay: $%.02f \n\n", c[i].np);
printf("\n");
}
}
void savetext(struct employee s[], struct calc c[], int n)
{
FILE *f;
f = fopen("employee.txt", "w");
for (int i = 0; i < n; i++)
{
fprintf(f, "%s\n", s[i].name);
fprintf(f, "%f %f %f %f\n", s[i].hoursWorked, s[i].hourlyRate, s[i].federalTax, s[i].stateTax);
fprintf(f, "%.2f %.2f %.2f %.2f\n", c[i].grosspay, c[i].fto, c[i].sto, c[i].np);
}
fclose(f);
}
void retrievetext(struct employee s[], struct calc c[], int n)
{
FILE *f;
int length;
f = fopen("employee.txt", "r");
for (int i = 0; i < n; i++)
{
fgets(s[i].name, sizeof(s[i].name), f);
length = (int)strlen(s[i].name);
s[i].name[length - 1] = '\0';
fscanf(f, "%f %f %f %f\n", &s[i].hoursWorked, &s[i].hourlyRate, &s[i].federalTax, &s[i].stateTax);
fscanf(f, "%.2f %.2f %.2f %.2f\n", &c[i].grosspay, &c[i].fto, &c[i].sto, &c[i].np);
}
fclose(f);
}
void savebin(struct employee s[], int n)
{
FILE *f;
f = fopen("employee.bin", "wb");
for (int i = 0; i < n; i++) {
fwrite(&s, sizeof(s[n]), n, f);
}
fclose(f);
}
void retrievebin(struct employee s[], int n)
{
FILE *f;
f = fopen("employee.bin", "rb");
for (int i = 0; i < n; i++) {
fread(&s, sizeof(s[i]), n, f);
}
fclose(f);
}
int main(){
savetext(st, c, 4);
retrievetext(st, c, 4);
printf("After reading text file");
print(st, c, 4);
savebin(st, 4);
retrievebin(st, 4);
printf("After reading bin file");
print(st, c, 4);
return 0;
}
You didn't get a warning here from this?
fscanf(f, "%.2f %.2f %.2f %.2f\n", &c[i].grosspay, &c[i].fto, &c[i].sto, &c[i].np);
fscanf() will eat any float you throw at it, specifying the %.2f format like this doesn't really work.
https://en.wikipedia.org/wiki/Scanf_format_string
Try using it like this:
fscanf(f, "%f %f %f %f\n", &c[i].grosspay, &c[i].fto, &c[i].sto, &c[i].np);
It was probably reading the file wrong, and then using the wrong line as an employee name.
PS: Your print() might have a small error:
for (int i = 0; i < 4; i++) // It should probably be i < n, instead of i < 4
And try to include an example input file, so people can test the code. At main(), there is no definition of st, so it's hard for people to see what's really happening if they can't test it themselves.
Thanks for all the answers, after the corrections the code did not work for a stupid error ... I opened both files with the same file pointer "database" ...
I've read dozens of questions like this but I can't get out of it, I'm going crazy.
The exercise that I have to do asks me to organize the items of a list in a file .txt that has elements of the type: Name Surname Age Wage, in alphabetical order according to the surname.
I have already created a function to insert the elements into the file and it works well.
I then went to the function to organize them but the process stops after the fscanf, and putting some test printf I saw that no values are assigned to the strings or that are assigned absurd numbers.
Please help ... thanks.
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 64
#define MAXFILE 100
void insert();
int fullcheck();
void sort();
typedef struct {
char name[MAX];
char surname[MAX];
int age;
double wage;
} data;
int main() {
insert();
return EXIT_SUCCESS;
}
void insert() {
char c;
int i;
data tmp;
FILE* database;
if ((fullcheck())>MAXFILE-1)
printf("Errore: database pieno.\n");
else {
database=fopen("database.txt", "a");
printf("Nome: ");
fgets(tmp.name, MAX, stdin);
tmp.name[strlen(tmp.name)-1]='\0';
printf("Cognome: ");
fgets(tmp.surname, MAX, stdin);
tmp.surname[strlen(tmp.surname)-1]='\0';
for (i=0; i<strlen(tmp.surname); i++) {
if (tmp.surname[i]==' ')
tmp.surname[i]='#';
}
printf("Eta': ");
scanf("%d", &tmp.age);
printf("Salario: ");
scanf("%lf", &tmp.wage);
while((c=getchar())!='\n');
fprintf(database, "%s %s %d %.0lf \n", tmp.name, tmp.surname, tmp.age, tmp.wage);
fflush(database); fclose(database);
if ((fullcheck())>1)
sort();
}
}
int fullcheck() {
char c;
int r=0;
FILE* database;
if ((database=fopen("database.txt", "r"))==NULL) {
return 0;
}
else {
while((c=getc(database))!=EOF) {
if(c=='\n')
r++;
}
return r;
}
}
void sort() {
char tmpstr[MAX];
int len=fullcheck(), i, a, b;
data tmp[len];
FILE* database;
FILE* sorted;
database=fopen("database.txt", "r");
database=fopen("sorted.txt", "w");
for (i=0; i<=len; i++) {
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
}
for (a=0 ; a<(len-1); a++) {
for (b=0; b<(len-1); b++) {
if ((tolower(tmp[b].surname[0]))>(tolower(tmp[b+1].surname[0]))) {
strcpy(tmpstr, tmp[b].surname);
strcpy(tmp[b].surname, tmp[b+1].surname);
strcpy(tmp[b+1].surname, tmpstr);
}
}
}
for (a=0; a<(len-1); a++) {
fprintf(sorted, "%s %s %d %.0lf \n", tmp[a].name, tmp[a].surname, tmp[a].age, tmp[a].wage);
}
fflush(database); fclose(database); remove("database.txt");
fflush(sorted); fclose(sorted); rename("sorted.txt", "database.txt");
}
Off by 1
Code attempts to read into len+1 elements of tmp[].
data tmp[len];
for (i=0; i<=len; i++) { // too many
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
}
I saw that no values are assigned to the strings (OP)
Better code would use width limits and test fscanf() result before using the data scanned.
// v---- < not <=
for (i=0; i<len; i++) {
if (fscanf(database, "%63s %63s %d %lf",
&tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage) != 4) {
// ^^^^ test!
break;
}
Even better code would read a line with fgets() into a stirng and then attempt to parse the string.
Off by 2
Code's attempt to find number of lines can be short by 1 if the last line does not end with a '\n'.
Alternative
size_t fullcheck(void) {
FILE* database = fopen("database.txt", "r");
if (database == NULL) {
return 0;
}
int previous = '\n';
int c;
size_t r=0;
while((c=getc(database))!=EOF) {
if (previous == '\n') r++;
previous = c;
}
fclose(database);
return r;
}
Missing fclose()
fullcheck() doesn't close the file after opening it.
int
Use an int to distinguish the typically 257 different returns values of fgetc(). Note when char` is unsinged, OP's code is an infinite loop.
More woes
The loop to print the sorted list is off-by-one, too short. And the sorting itself only looks at the first letter of each name, should use strcmp.
#user3386109
Maybe more?
Make sure to close the file here, before every return:
int fullcheck() {
char c;
int r=0;
FILE* database;
if ((database=fopen("database.txt", "r"))==NULL) {
fclose(database);
return 0;
}
else {
while((c=getc(database))!=EOF) {
if(c=='\n')
r++;
}
fclose(database);
return r;
}
}
And also a little bit fixing in the loop_counters here:
void sort() {
char tmpstr[MAX];
int len=fullcheck(), i, a, b;
data tmp[len];
FILE* database;
FILE* sorted;
database=fopen("database.txt", "r");
sorted=fopen("sorted.txt", "w+");
for (i=0; i<len; i++) {
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
printf("%s", tmp[b+1].surname);
system("pause");
}
for (a=0 ; a<(len); a++) {
for (b=0; b<(len); b++) {
if ((tolower(tmp[b].surname[0]))>(tolower(tmp[b+1].surname[0]))) {
strcpy(tmpstr, tmp[b].surname);
strcpy(tmp[b].surname, tmp[b+1].surname);
strcpy(tmp[b+1].surname, tmpstr);
printf("%s", tmp[b+1].surname);
system("pause");
}
}
}
for (a=0; a<(len); a++) {
fprintf(sorted, "%s %s %d %.0lf \n", tmp[a].name, tmp[a].surname, tmp[a].age, tmp[a].wage);
}
fclose(sorted);
fclose(database);
}
I am trying to read numbers from file, the function prints only the digits after the decimal point. any idea why this happens?
thanks!
float Read() {
int i, k, w, m, n, j;
float number;
float a[m];
FILE *fil1;
fil1 = fopen("numbers.txt", "r");
w = 0; k = 0;
while (fscanf(fil1, "%d", &n) != EOF) {
fscanf(fil1, "%f", &number);
a[k] = number;
printf("%d => %f \n", i, a[k]);
w++;k++;
}
}
You're scanning the file twice, you're basically skipping every second number. this should fix it.
float Read (){
int i,k,w,m,n,j;
float number;
float a[m];
FILE *fil1;
fil1 = fopen("numbers.txt","r");
w=0; k = 0;
while (fscanf(fil1, "%f", &n) != EOF){
a[k]=n;
printf ("%d => %f \n",i, a[k]);
w++;k++;}
change n to be float
and read it as float:
#include "stdio.h"
#pragma warning(disable : 4996)
float Read()
{
int k, w;
float n;
float a[100];
FILE* fil1;
fil1 = fopen("numbers.txt", "r");
w = 0; k = 0;
while (fscanf(fil1, "%f", &n) != EOF) {
a[k] = n;
printf("%f \n", a[k]);
w++; k++;
}
return 0;
}
Totals different for same file when executed.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_FILE_NAME 100
#define RUNS 1
int main() {
int num,i;
FILE *fp;
char*s, buf[1024];
int count =0;
char c;
char filename[MAX_FILE_NAME];
printf("Enter filename: ");
scanf ("%s",filename);
if ((fp =fopen(filename, "r")) == NULL) {
printf("Error");
exit(1);
}
fscanf(fp,"%d",&num);
for (c = getc(fp); c!= EOF; c = getc(fp))
{
if (c == '\n'){
count = count+1;
}
}
printf("%s has %d numbers \n", filename, count);
int f;
printf("Choose from the options how many processes you want to use [1,2,4]: ");
scanf("%i", &f);
printf("%i processes \n", f);
int fds[f+1][2];
int numb[count];
int x,k;
time_t start, finish;
start = time(NULL);
for(i = 0; i < RUNS; i++)
{
pipe(fds[f]);
for( x = 0; x<f; x++)
{
pipe(fds[x]);
int ind[2];
ind[0] = ((x)*(count/f));
ind[1] = ((x+1)*(count/f));
write(fds[x][1], &ind, 2* sizeof(int));
if (fork() ==0)
{
int t =0;
int ind2[2];
read(fds[x][0], &ind2, 2*sizeof(int));
for( k = ind2[0]; k<ind2[1]; k++)
{
t += numb[k];
}
write(fds[f][1], &t, sizeof(int));
exit(0);
}
}
int m, tmp, total;
total = 0;
for( m = 0; m < f; m++)
{
for( m = 0; m < f; m++)
{
read(fds[f][0], &tmp, sizeof(int));
sleep(5);
total += tmp;
}
printf("DOne calc \n");
printf("Total: %i \n", total);
}
finish = time(NULL);
float runtime = (float)((finish-start)/RUNS);
printf("runtime: %f \n", runtime);
fclose(fp);
return 0;
}
You get random result for the same input because the calculation based on uninitialized int numb[count]; values.
According to the C99 standard, section 6.7.8.10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
Because of it int numb[count]; contains some random junk from memory. To get predictive results use explicit initialization:
#include <string.h> // memset
int numb[count];
memset (numb, 0, sizeof(numb)); // Zero-fills
Use the code bellow to put numbers from filename file into numb:
int i = 0;
char line[1024];
fseek(fp, 0, SEEK_SET);
while(fgets(line, sizeof(line), fp) )
{
if( sscanf(line, "%d", &numb[i]) == 1 ) // One number per line
{
++i;
}
}