Jump to content

First writing and then reading, reopen ?

- - - - -

  • Please log in to reply
2 replies to this topic

#1
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts
Hey,

I'm creating a small unit test in which I first write something to a file and then I'm going to check if it's good. So the file doesn't exist in the beginning and I'll open it up with fopen(filename, "w"). When I then read it should I first close it and reopen or just reopen in read-mode ?

#2
dbug

dbug

    Programmer

  • Members
  • PipPipPipPip
  • 155 posts
If you open the file in write only mode ("w"), then you must close and reopen it in read only ("r") or read-write ("rw") mode to be able to read it.

Another option is opening the file in read-write mode from the begining and, after writing, use fseek to go to the begining of the file and start reading it without having to close and reopen.

EDIT: if you are doing this to verify if the file has been correctly written to the disk, this might not be the best way to do it. Due to operating system caching on the file system, it's very probable that what you read comes directly from memory instead of disk. So you aren't really verifying if it has been correctly written physically.

Edited by dbug, 22 October 2010 - 12:23 AM.
add more information


#3
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts
  • Programming Language:C, Java, C++, PHP, Python, Perl, Assembly, Bash, Others
  • Learning:JavaScript

FILE *f = fopen(output_file, "w");


/* do your output stuff here */


f = freopen(output_file, "r", f);

/* do reading stuff here */


Alternatively:

FILE *f = fopen(output_file, "rw");


/* output stuff here */

fflush(f);


/* reading stuff here */


sudo rm -rf /




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users