-2

I' m trying to write to a file. It' s created properly but can not write nothing. On debug mode, I can see all attributes of object which I want to write.

My method is so short, I used fseek method before writing.

void File::add(record *ptr){
   fseek(book, 0, SEEK_END);
   fwrite(ptr, sizeof(record), 1, book);
} 

After running the program, I check the file, it' s created empty. The file is the same directory with my source files

alperk
  • 15
  • 3
  • 1
    You have no error checking in that code at all - both `fseek` and `fwrite` return a status - you should check this in both cases. – Paul R Sep 17 '14 at 21:14
  • fseek method returns 0 and fwrite returns 1. Does not it seem working? – alperk Sep 17 '14 at 21:20
  • 1
    OK - that's what you would expect - so the problem lies elsewhere. Try and get into the habit of always adding error checking in future though. You'll probably need to post more of your code if you still need help debugging this, particularly the parts that open/close the file, and anywhere else where you might call `fseek` or `fsetpos`. One further comment: in a modern C++ program you should really be using proper C++ file I/O, not the old C library calls. – Paul R Sep 17 '14 at 21:23
  • Thanks to your advice about proper open/close the file, problem is solved. Thank you! – alperk Sep 17 '14 at 21:33
  • Did you remember to flush ... after a write? – Thomas Matthews Sep 18 '14 at 00:26

1 Answers1

0

Try using fputs instead of fwrite:

/* fseek example */
#include <stdio.h>

int main ()
{
  FILE * pFile;
  pFile = fopen ( "example.txt" , "wb" );
  fputs ( "This is an apple." , pFile );
  fseek ( pFile , 9 , SEEK_SET );
  fputs ( " sam" , pFile );
  fclose ( pFile );
  return 0;
}
nrussell
  • 18,382
  • 4
  • 47
  • 60
John smith
  • 160
  • 6