Hello, my name is Egal and I'd like to post here a serious (but simple, I think) doubt about this simple writing & reading code.
The idea is quite easy: I create the void routine write() that writes the value of a double "number" in a new file called "document.dat". Then I create another void routine, read(), which reads the writed value and prints it by console.
Inside main() I invoke both routines directly, one after the other, and I expect to obtain a value of 0.500000.
Code:
/* File: main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void write(){
FILE *file1;
double number = 0.5;
file1 = fopen("document.dat","w+");
fprintf(file1,"%f\n",number);
fclose(file1);
}
void read(char filepath[]){
FILE *file;
char buffer[0x8];
double r;
file = fopen(filepath,"r+");
fseek(file, 0x0, SEEK_SET);
fread(buffer, strlen(buffer), 1, file);
sscanf(buffer, "%lf", &r);
if(r!=0.000000){
printf("Value: %f\n", r);}
fclose(file);
}
int main() {
write();
read("document.dat");
/*FILE *file;
char buffer[0x8];
double r;
file = fopen("document.dat","r+");
fseek(file, 0x0, SEEK_SET);
fread(buffer, strlen(buffer), 1, file);
sscanf(buffer, "%lf", &r);
if(r!=0.000000){
printf("Value: %f\n", r);}
fclose(file);*/
return (EXIT_SUCCESS);
}
The thing is, when I compile (using the linux gcc compiler) just like you can see in the code, the terminal prints 0.000000. But if I try reading only the recentrly created document.dat file without invoking write(), the console prints 0.50000 correctly. This means that write() is creating the file correctly and there must be an error between write() and read() execution. This is weird, since both are independent and, if I'm not mistaken, read() cannot be executed if write() execution hasn't been completed (and hence, the file has been closed and ready to be read).
But just in case, I've modified the code, and write the read() rotuine explicitly inside main():
Code:
/* File: main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void write(){
FILE *file1;
double number = 0.5;
file1 = fopen("document.dat","w+");
fprintf(file1,"%f\n",number);
fclose(file1);
}
void read(char filepath[]){
FILE *file;
char buffer[0x8];
double r;
file = fopen(filepath,"r+");
fseek(file, 0x0, SEEK_SET);
fread(buffer, strlen(buffer), 1, file);
sscanf(buffer, "%lf", &r);
if(r!=0.000000){
printf("Value: %f\n", r);}
fclose(file);
}
int main() {
write();
//read("document.dat");
FILE *file;
char buffer[0x8];
double r;
file = fopen("document.dat","r+");
fseek(file, 0x0, SEEK_SET);
fread(buffer, strlen(buffer), 1, file);
sscanf(buffer, "%lf", &r);
if(r!=0.000000){
printf("Value: %f\n", r);}
fclose(file);
return (EXIT_SUCCESS);
}
and surprisingly it works (prints 0.500000).
Funny thing is, if I compile in MAC with it's corresponding gcc compiler, the first code works fine too.
Any idea about why is this?