Ideally, I would like to be able to tell my program "autocorrelation *.txt" in a directory and have it process each file in the directory, returning each file's results to a new file ending in "-AUTO.txt"
For example, if I had APPLE.txt, BANANA.txt, and ORANGE.txt, this program should be returning the files APPLE-AUTO.txt, BANANA-AUTO.txt, and ORANGE-AUTO.txt after running "autocorrelation.exe"
Instead, I'm seg faulting. What am I doing wrong?
Code:
/*********************************************************************
* This program is designed to calculate a series of autocorrelations *
* based on a set of data that is called when the program is run. *
* The set of data needs to be in "float" format (i.e., nothing but *
* numbers), or else the program will generate an error. The *
* resulting file will also be a series of numbers, meant to go into *
* some kind of graphing program to plot the original data against *
* the values of the autocorrelations for each point. *
*********************************************************************/
/* Autocorrelation Program, Written By Don Ford */
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE* dataFile;
FILE* outputFile;
char string[80];
char *old_filename;
char new_filename[256];
char * ext;
double x[1000];
int i = 0;
int j;
int number_of_values;
double x_sum = 0.0;
double x_average;
double values = number_of_values;
int k;
int t;
double y[number_of_values];
double sum_of_squares = 0.0;
double numerator = 0.0;
char buffer[80];
for (j=1; j<argc; j++){
old_filename = argv[j];
dataFile = fopen(argv[j], "r");
if (dataFile == NULL){
fputs("File error", stderr);
exit(1);
}
while (fgets(string, 80, dataFile) != NULL){
if (!isalpha(string[0])){
x[i] = strtof(string, NULL);
i++;
}
}
fclose(dataFile);
number_of_values = i;
for (i=0; i<number_of_values; i++){
x_sum += x[i];
}
x_average = (x_sum/values);
/* Now, we actually calculate the autocorrelation! */
for (t=0; t<number_of_values; t++){
sum_of_squares += ((x[t] - x_average)*(x[t] - x_average));
}
for (k=0; k<(number_of_values/2); k++){
for (t=0; t<(number_of_values - k); t++){
numerator += ((x[(t+k)] - x_average)*(x[t] - x_average));
}
y[k] = (numerator/sum_of_squares);
numerator = 0.0;
}
ext = strrchr(old_filename, '.');
strncpy(new_filename, old_filename, argv[j]-ext+1);
strcat(new_filename, "-AUTO.txt");
printf("\"%s\" created.\n", new_filename);
outputFile = fopen(new_filename, "wb");
if (outputFile == NULL){
fputs("File error", stderr);
exit(2);
}
snprintf(buffer, 80, "Lag%4Autocorrelation\0");
fputs(buffer, outputFile);
fputs("\n", outputFile);
snprintf(buffer, 80, "---%4---------------\0");
fputs(buffer, outputFile);
fputs("\n", outputFile);
for (i=0; i<(number_of_values/2); i++){
snprintf(buffer, 80, "%2d%10.8f\0", i, y[i]);
fputs(buffer, outputFile);
fputs("\n", outputFile);
}
fclose(outputFile);
}
return 0;
}