A
akang2005
When I write 'double' data to the file, it seems working fine, but when
I read it later, it returns a eof when it encounters a particular
number even the file is not at the end yet. However, while I write a
different set of data, there is no problem to read it.
Attached is the file: try change the #define RANGE 1000 into 10000,
the code works when the number is 1000, and does not work when the
number is 10000.
// trw.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
#define NUM 2000
#define RANGE 1000
short initWrite (char *fileStr) {
FILE *fp;
//srand( (unsigned)time( NULL ) );
fp = fopen(fileStr, "w");
if (!fp) {
return -2;
}
size_t i = 0;
double t[NUM];
for (i=0; i<NUM; i++) {
if (i == 345)
t = 0;
else
t = rand () * RANGE/RAND_MAX;
}
i = fwrite (t, sizeof(double), NUM, fp);
fflush (fp);
fclose (fp);
return i;
}
short initRead (char *fileStr) {
FILE *fp;
//srand( (unsigned)time( NULL ) );
fp = fopen(fileStr, "r");
if (!fp) {
return -2;
}
double t[NUM];
fseek (fp, 0, SEEK_SET);
size_t i = fread (t, sizeof(double), NUM, fp);
if (feof (fp)) {
fprintf (stderr, "End of reading file\n");
}
else if (ferror(fp))
perror ("What;s wrong");
fclose (fp);
return !(i==NUM);
}
int _tmain(int argc, _TCHAR* argv[])
{
char *str = "D:/test.dat";
initWrite (str);
if (!initRead (str))
printf ("Good\n");
else
printf ("Something wrong\n");
/* for (int i=0; i<10000; i++) {
double f = updateFile (str);
if (!(i%10))
printf ("data is %5.2f\n", f);
}
*/
return 0;
}
I read it later, it returns a eof when it encounters a particular
number even the file is not at the end yet. However, while I write a
different set of data, there is no problem to read it.
Attached is the file: try change the #define RANGE 1000 into 10000,
the code works when the number is 1000, and does not work when the
number is 10000.
// trw.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
#define NUM 2000
#define RANGE 1000
short initWrite (char *fileStr) {
FILE *fp;
//srand( (unsigned)time( NULL ) );
fp = fopen(fileStr, "w");
if (!fp) {
return -2;
}
size_t i = 0;
double t[NUM];
for (i=0; i<NUM; i++) {
if (i == 345)
t = 0;
else
t = rand () * RANGE/RAND_MAX;
}
i = fwrite (t, sizeof(double), NUM, fp);
fflush (fp);
fclose (fp);
return i;
}
short initRead (char *fileStr) {
FILE *fp;
//srand( (unsigned)time( NULL ) );
fp = fopen(fileStr, "r");
if (!fp) {
return -2;
}
double t[NUM];
fseek (fp, 0, SEEK_SET);
size_t i = fread (t, sizeof(double), NUM, fp);
if (feof (fp)) {
fprintf (stderr, "End of reading file\n");
}
else if (ferror(fp))
perror ("What;s wrong");
fclose (fp);
return !(i==NUM);
}
int _tmain(int argc, _TCHAR* argv[])
{
char *str = "D:/test.dat";
initWrite (str);
if (!initRead (str))
printf ("Good\n");
else
printf ("Something wrong\n");
/* for (int i=0; i<10000; i++) {
double f = updateFile (str);
if (!(i%10))
printf ("data is %5.2f\n", f);
}
*/
return 0;
}