View Single Post
  #2 (permalink)  
Old 09-09-04, 04:26 PM
Sokolov Sokolov is offline
Newbie Coder
 
Join Date: Sep 2004
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Hi Adam,

Your code looks fie, nothing wrong. Maybe you need to check if you opened the file correctly. Also check the return value of the read function.

Here a simple C and C++ exaple of writing and reading a number from file (binary):
Code:
#include <stdio.h>
#include <stdlib.h>


int main(void)
{
   FILE *fp;
   int number = 9;
   char *filename = "c:\\test.bin";

   if((fp = fopen(filename, "wb")) == NULL)
   {
      perror(filename);
      return EXIT_FAILURE;
   }

   fwrite(&number, sizeof number, 1, fp);
   fclose(fp);

   if((fp = fopen(filename, "rb")) == NULL)
   {
      perror(filename);
      return EXIT_FAILURE;
   }

   fread(&number, sizeof number, 1, fp);
   printf("number = %d\n", number);
   fclose(fp);
   return EXIT_SUCCESS;
}
Code:
#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
   char *filename = "c:\\test.bin";
   int number = 9;
	
   ofstream out(filename, ios::out|ios::binary);

   if(!out.is_open()) 
   {
      cerr << "Error opening output file" << endl;
      return EXIT_FAILURE;
   }
   out.write((char *)&number, sizeof number);
   out.close();

   std::ifstream in(filename, ios::in|ios::binary);
	
   if(!in.is_open()) 
   {
      cerr << "Error opening input file" << endl;
      return EXIT_FAILURE;
   }
   in.read((char *)&number, sizeof number);
   cout << "number = "<< number << endl;
   in.close();

   return EXIT_SUCCESS;
}
Reply With Quote