Thursday 22 December 2011

using fopen and fread with /dev/sda

using fopen and fread with /dev/sda

Last night I accidentally deleted quite a few files I had been working on for the past month or so. So, after freaking out for a little while and after trying unsuccessfully to use grep on the unmounted partition (it ran out of memory...haha) I decided I may as well learn something from this and so I am using another computer to write a program (in c) to read directly from my hard drive (/dev/sda) and search for a specific string while using only a reasonable amount of memory (grep was using all 8GB). I now have my computer I deleted the files on running off of a flash drive so that it doesn't harm the data on the hard drive, but I have a few questions about using fopen and fread to read data from /dev/sda (sorry if I have too many questions...I just want to be certain this will work):

Would fopen treat /dev/sda just like any other file?

When using fread on a /dev/sd* file will it return less than the requested bytes when it gets to the end of the hard drive?

Would fread read directly from /dev/sda or would it try to copy it into memory first? Do I have to worry about memory problems if I try to read another 100MB after already reading 8GB (the amount of memory I have on my computer) even though I have free'd the memory that I had it read into?

My program as I have it functions more or less as follows:
Code:

FILE* inputStream = fopen("/dev/sda", "rb");
//...stuff to check to make sure it actually opened it

//...

//...the following is inside of a loop...
char* memoryChunk = malloc(100000000); //allocate 100mb for the chunk to be read
unsigned long int actualReadBytes = fread(memoryChunk, 1, 100000000, inputStream);
//...memoryChunk is processed...
free(memoryChunk);
if (actualReadBytes < 100000000)
{
      //...exit the loop since that means the last chunk read was the end of /dev/sda
}

//...after the loop and everything
fclose(inputStream);

No comments:

Post a Comment