Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
My code is very simple one. But, I don't know what's wrong with my code. I can't know this error even after spending 3 hours. Here is my problem.
"Random value are saved in file. When I read these data from file, the results are all 0.00". What's wrong with my code? Thanks in advanced for your help and time.

C#
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define DATALENGTH 10

void main()
{
    FILE* fp;
    int err_no = fopen_s(&fp, "C:\\Tests\\test.dat", "wb");
    if (err_no != 0) {
        printf("file open error.");
        _getch();
    }

    double data = 0.00;
    for (int i = 0; i < DATALENGTH; i++) {
        data = rand()%100;
        fprintf(fp, "%lf", data);
    }

    fclose(fp);

    FILE* fp_read;
    err_no = fopen_s(&fp_read, "C:\\Tests\\test.dat", "r");
    if (err_no != 0) {
        printf("file read error.");
        _getch();
    }

    double* buffer = (double*)malloc(sizeof(double) * DATALENGTH);
    int data_len = fread(buffer, sizeof(double), DATALENGTH, fp_read);
    if (data_len != DATALENGTH) {
        printf("File read failed.");
        getch();
    }
    fclose(fp_read);

    for (int j = 0; j < DATALENGTH; j++) {
        printf("buffer[%d] == %.2lf\n ", j, buffer[j]);
    }
    _getch();
}
Posted
Comments
Sergey Alexandrovich Kryukov 11-Apr-12 12:10pm    
First of all, how do you the data in the file not zeros? Did you open the file in the binary editor/viewer to check it up?
--SA
April2004 11-Apr-12 12:15pm    
Check contents by dragging .dat file to notepad.
Here I found the data in file.
41.000000 67.000000 34.000000 0.000000 69.000000 24.000000 78.000000 58.000000 62.000000 64.000000
Schehaider_Aymen 11-Apr-12 12:22pm    
Try to use a char* when you read the content of your file then cast the slices to double.
Sergey Alexandrovich Kryukov 11-Apr-12 12:23pm    
Is there a specific reason to write C code in C++ file?
--SA

Have a look at your data in the file - it is not what you think it is.
What you will have is a string representation of the numbers with 6 digits of precision, that may or may not vary in length depending on the number of digits in the random number you first generated (0-9 may give you a shorter value that 10-99)

You then read this back as binary data and try to interpret it as double values.
No. It's not going to give you what you expect. Not even close.

Instead, try writing it with a data terminator (comma say, or new line) and reading it back as a string then converting it to a double.
Or convert the original number to a double, and save that as binary data.

Your choice.
 
Share this answer
 
This code makes no sense: just look what is written in the output file. You have written some floating-point numbers in human-readable string representation, without any delimiters between the values; due to casualty of the format, some "records" take 9 bytes, some other take 8. You should not have written it in first place — what's the use?

Then you open the file for reading and try to read it as an array of double-precision floating-point numbers, 8 bytes each. You write in one format, which makes no practical sense, because it does not allow for unambiguous interpretation (due to lack of fixed boundaries between records), and read in totally unrelated format. This is nothing but a mess.

There is no a fix, because apparently there is no functional purpose in this code, so I assume the purpose is learning how data is presented, read and written. It can be done in different ways, and you will need to learn them all. First, you need to write data in many different ways and see how it looks. As you are a beginner, I would advise you use both text and binary editors and examine how the data is laid out. When you get a grip on what's going on, think about reading it.

Some side advice: don't use obsolete getch, use _getch. Never use hard-coded absolute file path, even in the research/study code, use relative; in your case, it could be just the file name without directory, so the actual location will be defined by the current working directory. Remember, in the final product, there are no situations when a hard-coded path can be used. Never repeat any data; you have written "C:\\Tests\\test.dat" twice, which is totally unsupportable. Define it as an explicit constant, only once. Please see: http://en.wikipedia.org/wiki/Don%27t_repeat_yourself[^]. Failing to follow this very basic principle is the invitation for all kinds of trouble.

By the way, how about writing at least a bit in C++, not C, once your file is *.cpp? Avoid #define, use const int length = 10; instead. But if you want to lean C, as opposed to C++, create a *.C file.

—SA
 
Share this answer
 
v3
Comments
Espen Harlinn 11-Apr-12 16:17pm    
5'ed!
Sergey Alexandrovich Kryukov 11-Apr-12 16:19pm    
Thank you, Espen.
--SA
There is nothing wrong in writing or reading the .dat file. The only thing going wrong is how you show it in console

try this out

C++
for (int j = 0; j < sizeof(double)*10; j++)
 {
        //printf("buffer[%d] == %.2lf\n ", j, buffer[j]);
        printf("%c", ((char *)buffer)[j]);
}


[EDIT]

And the out put I got is
41.00000067.00000034.0000000.00000069.00000024.00000078.00000058.00000062.000000

And you can format this to have space between each or can go for new line
 
Share this answer
 
v2
Comments
Lakamraju Raghuram 11-Apr-12 12:29pm    
The suggestions specified by other are worth following. Give them a shot
April2004 11-Apr-12 12:34pm    
Great! I got the expected output after trying with your code. Thank you very much.
Actually, not only for printing in console, my purpose is also to save this double data in local double array. How should I do? Do I need to convert Char to Double?
Schehaider_Aymen 11-Apr-12 12:37pm    
yes, that is what calling casting data.
Lakamraju Raghuram 11-Apr-12 12:49pm    
yes. Correct. sorry I missed your statement above.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900