Monday, August 17, 2009

Perl to C

# --------------------------------------------*
# Program mylib.pl *
# This program generates a summary *

# declare and initialize variables
my $count,@lines,$sum,$max,$min,$time, $motion;

# open file and read the number of data points
open(FILE,"<readfile.dat") or die "Can't open file $!\n";

# read data and compute summary information
while(my $line = <file>) {
my($time, $motion) = split(/\s/, $line,2);
$count++; if($count ==1 ) {$max = $min = $motion;}
$sum += $motion;
if($motion > $max ) {
$max = $motion;
}
if($motion < $min) {
$min = $motion;
}
}
# print summary information

print "\nNumber of sensor readings: $count\n";
printf("Average reading: %.2f\n", $sum/$count);
printf("Maximum reading: %.2f\n", $max);
printf("Minumum reading: %.2f\n", $min);
# close file and exit program
close(FILE);

#>+++++++++++++ In C

/*--------------------------------------------*/
/* Program mylib.c */
/* This program generates a summary */
/* report from a data file that has */
/* the number of data points in the first row */
#include <stdio.h>
#include <stdlib.h>
#define FILENAME "readfile.dat"
int main(void)
{
/* declare and initialize variables */
int num_data_points, k;
double time, motion, sum=0,max, min;
FILE *sensor1;
/* open file and read the number of data points */
sensor1 = fopen(FILENAME, "r");
if(sensor1 == NULL)
{
printf("Error opening input file\n");
} else {
fscanf(sensor1, "%i",&num_data_points);
/* read data and compute summary information */
while((fscanf(sensor1, "%lf %lf",&time,&motion)) == 2)
{
num_data_points++;
if( num_data_points == 1 )
max = min = motion;
sum += motion;
if(motion > max)
max = motion;
if(motion < min)
min = motion;
} /* end of for */
/* print summary information */
printf("Number of sensor readings: %i \n", num_data_points);
printf("Average reading: %.2f \n", sum/num_data_points);
printf("Maximum reading: %.2f \n", max);
printf("Minmum reading: %.2f \n", min);
/* close file and exit program */
fclose(sensor1);
} /* end of if */
return EXIT_SUCCESS;
} /* end of main */

#>++++++ Data file readfile.dat

0.0 132.5
0.1 147.2
0.2 148.3
0.3 157.3
0.4 163.2
0.5 158.2
0.6 169.3
0.7 148.2
0.8 137.6
0.9 135.9