Print data of a file stored in file pointer in C

2k Views Asked by At

I have written content to a file using a file pointer. I would now like to print this data in the form of an array. I am new to programming in C, and it looks like printing file pointers is different.

Here is an example of my code,

int main(){

    double a=0;
    double b=0;
    double c=0;
    double d=0;

    int bufferLength = 330752;
    char buffer[bufferLength];

    FILE *fp = fopen("original.dat", "r");
    if (!fp){
        printf("Cant open the original file\n");
        return -1;
    }

    FILE *fp1 = fopen("24bitnoise.dat", "r");
    if (!fp1){
        printf("Cant open the noise file\n");
        return -1;
    }

    FILE *outfp= fopen("out.dat", "w");
    if(outfp == NULL)
    {
        printf("Unable to create file\n");
    }
    while(fgets(buffer, bufferLength, fp)) {      
        if (2==sscanf(buffer, "%lf %lf", &a,&b)){  // Just printing col 2 //
            // printf("b: %f\n", b);
            fprintf(outfp, "%0.25f\n", b);
        }
    }

    FILE *noisefp= fopen("outnoise.dat", "w");
    if(noisefp == NULL)
    {
        printf("Unable to create file\n");
    }

    while(fgets(buffer, bufferLength, fp1)) {     
        if (2==sscanf(buffer, "%lf %lf", &c,&d)){  // Just printing col 2 //

            fprintf(noisefp, "%0.25f\n", d);
        }
    }
    printf("%f", outfp);
    printf("File transferred\n");
    fclose(outfp);
    fclose(fp);
    fclose(fp1);
    fclose(noisefp);
    return 0;
}

I would now like to print the values from *outfp in the form of an array.

1

There are 1 best solutions below

0
chux - Reinstate Monica On

OP is attempting, incorrectly, to print the contents of a file with

printf("%f", outfp);

"%f" expects a matching double, not a FILE *.


To print the text contents of a file, line-by-line:

FILE *inf = fopen("out.dat", "r");
if (inf) {
  while(fgets(buffer, bufferLength, inf)) {
    printf("%s", buffer);
  }
  fclose(inf);
}

how can I put these values into an array?

The "trick" is how to determine the size of the array.

One simple approach:

size_t count = 0;
while(fgets(buffer, bufferLength, fp)) {      
  if (2==sscanf(buffer, "%lf %lf", &a,&b)) {
    count++;
  }
}

double fp_array = malloc(sizeof *fp_array * count);
if (fp_array == NULL) Handle_Out_of_memory();  // Some tbd code

// Read again
rewind(fp);
size_t i = 0;
while(fgets(buffer, bufferLength, fp)) {      
  if (2==sscanf(buffer, "%lf %lf", &a,&b)) {
    fp_array[i++] = b;
  }
}

// Use fp_array

free(fp_array);  // clean up when done.

A more elegant approach would re-size the allocation as needed and perform only one read pass.