LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   binary file problem (https://www.linuxquestions.org/questions/programming-9/binary-file-problem-287860/)

vrdhananjay 02-08-2005 05:48 PM

binary file problem
 
okay this is a piece of code....

int fdf;
int rcf;
fdf=open("output7",O_WRONLY|O_CREAT|O_TRUNC,0666);
rcf=write(fdf,genespect,len);
close(fdf);

genespect is pointer to a double array
it was declared as

double *genespect;

genespect=(double*)malloc(len*sizeof(double));

after the execution i see that the file output7 has been made.it probably has
legit data too...i cant open it....gedit does not open it .....

i basically want this to be an ascii file with one number per line...
how do i do that?
i know it isnt like that cos' gnuplot isnt able to plot it(it requires the file to be in one number per line format)

thanks,
dhananjay

itsme86 02-08-2005 06:01 PM

You're best off using stdio functions:
Code:

fp = fopen("output7", "w");
for(i = 0;i < len;++i)
  fprintf(fp, "%f\n", genespect[i]);
fclose(fp);

"binary files" and "one number per line" don't mix. Binary files have no concept of newlines so they also don't have any concept of lines.

Hko 02-08-2005 06:11 PM

itsme86 already told, but I'd already made up an example. I'll post it anyway.
Code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, len;
    double *genespect;
    FILE *file;

    len = 2;
    genespect = calloc(len, sizeof(double));
    if (genespect == NULL) {
        fprintf(stderr, "Error: Ouot of memory\n");
        return 1;
    }
   
    /* Just two values here */
    genespect[0] = 22.0/7.0;
    genespect[1] = 355.0/113.0;

    /* Open file */
    /* Using higher level stdio here */
    file = fopen("output.txt", "w");
    if (file ==NULL) {
        perror("Opening output file.");
        return 1;
    }

    for (i = 0; i < len ; ++i) {
        /* Using stdio calls you can do convenient
        * printf-conversion while writing to a file.
        */
        fprintf(file, "Value #%d: %f\n", i, genespect[i]);
    }
    fclose(file);
    return 0;
}


vrdhananjay 02-08-2005 06:33 PM

Seriously man,you guys are lifesavers!!!!!!
it worked!!
dhananjay


All times are GMT -5. The time now is 06:02 AM.