-1

I need to write the content of an array into a file. Let's suppose I generate random numbers and put them into an array. How do I copy those values into the output file?

[... previous code/declarations ...]

file = open(filename, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU|S_IWGRP|S_IWOTH);
buffer = (double *) calloc(d, sizeof(double));
for (i = 0; i < d; i++)
{
    double div = (double) (RAND_MAX/0.333);
    double r = rand()/div;
    (*(buffer+i)) = r;
}
write(file, buffer, sizeof(double));

[ ... ]

If I try to read the files, all I see is this memory garbage, nonsense chars all over my screen. Can anyone please help me figuring out what is I do wrong?

1
  • 1
    When you say "read the files", do you mean using cat? If you read them using read or fread, you will see that the values are perfectly reasonable (albeit random) values. Try using xxd instead of cat if you want to view the content from a terminal. May 24, 2011 at 12:18

4 Answers 4

2

The write call is used to write memory blocks to a file, which will seem like garbage mostly if you try to just output the file later. That's because they will most likely be an IEEE754 binary representation.

If you want a textual representation of the numbers, use something like:

fh = fopen (filename, "w");
for (i = 0; i < d; i++)
    fprintf (fh, "%f\n", buffer[i]);
fclose (fh);
1
  • Garbage or not visible at all, depending on the text viewer and what came out first as random number. May 24, 2011 at 8:54
1

You are writing random binary values to the file. When you read the file, you see the random binary values, interpreted as characters. Where's the problem?

3
  • Actually I don't see them. If I perform a cat on the output file I get strange chars and as I try to read from the file, in order to print the values on the screen, nothing is displayed.
    – haunted85
    May 24, 2011 at 8:52
  • Those "strange characters" are the textual representation of your random binary values.
    – user2100815
    May 24, 2011 at 8:53
  • @haunted85, Neil misunderstood what you wanted. See paxdiablos' answer. May 24, 2011 at 8:53
0

At least this part is wrong:

write(file, buffer, sizeof(double));

You're writing only a single value, not the whole array. Multiply the size with d (which seems to be the number of elements in your array).

1
  • How can I make myself sure to write into the file all my elements, is it enough increase the size? Don't I need a loop?
    – haunted85
    May 25, 2011 at 8:17
0

Why do you put

double div = (double) (RAND_MAX/0.333);

inside the loop?

1
  • You are right, I shouldn't. That is a mistake. I wasn't paying too much attention to the algorithm itself, I'm trying to figure out how write() and read() work.
    – haunted85
    May 25, 2011 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.