Segmentation Fault when writing to a file in C

I have a program called test-usb20X that runs a function called fastResults() when I run it with an argument. For some reason I keep getting a segmentation fault when trying to write to a file in the function. It creates the file successfully but nothing gets written to it.

My code:

int fastResults(){
    FILE *f = fopen(fileName, "a");
    if (f == NULL) {
            printf("Error opening file!n");
    printf("nSample #%dn", j);
    fprintf(stdout, "Timestamp = %un", (unsigned)time(NULL));  
    fprintf(f, "%u,",(unsigned)time(NULL));
    for (i = 0; i < 8; i++) {
        value = usbAIn_USB20X(udev, i);
            value = rint(value*table_AIN[7][0] + table_AIN[7][1]);
            printf("Channel %d   Voltage = %lf", i, value, volts_USB20X(udev,value));
            measurement = channels[i].gain * volts_USB20X(udev,value) + channels[i].offset;
            printf("   Measurement = %.4fn", measurement);     
            fprintf(f, "%.4f,", measurement);
    fprintf(f, "n");
    return 0;

My Output:

Sample #0
Timestamp = 1435912692
Segmentation fault (core dumped)

It seems as though it successfully prints to the program but not into the file.

Source: c#

Leave a Reply