Results 1 to 2 of 2
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 ...
- 12-22-2011 #1Just Joined!
- Join Date
- Jul 2008
- Posts
- 3
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);
- 12-23-2011 #2Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
Yes, though you should open it read-only.Would fopen treat /dev/sda just like any other file?
It should. You should check errno or the feof(stream) to determine whether or not this is an error or just the end of the "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?
FWIW, you can reuse the memoryChunk you allocated for subsequent reads - much more efficient that repeated malloc/free cycles. The system will free the memory when the process terminates.Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!


Reply With Quote