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.
OP is attempting, incorrectly, to print the contents of a file with
"%f"expects a matchingdouble, not aFILE *.To print the text contents of a file, line-by-line:
The "trick" is how to determine the size of the array.
One simple approach:
A more elegant approach would re-size the allocation as needed and perform only one read pass.