Search code examples
cjpegdirectory-structurecs50recovery

Accessing a different drive in c


I want to scan a directory, checking for JPEG-files (i.e. the combination of the first few bytes) and copying them to another drive. I successfully tested that program and it screens documents. However, I cannot access a whole directory (e.g. my accidentally erased SD-Card in D:/).

Here is how I tried to access it:

// remember the path from the command line
char *path = argv[1];

// open the path (preferably "D:\" - which is my SD-Card ;))
FILE *inptr = fopen(path, "r");
if (inptr == NULL)
{
    fprintf(stderr, "inputfile could not be read\n");
    return 1;
}

The output is "inputfile could not be read" - which is why I am quite confident that the error is right there. Do I need to address a directory differently? E.g. by using a pointer to the first bit of the drive?

I am a beginner - so please be gentle while laughing. ;)

Thank you very much! Marcel


Solution

  • 'fopen()' cannot open an entire directory or drive, it can only open a specific path. However, there are ways to accomplish the task of listing all files in a directory. This answer already contains some pertinent information.

    Since you can already open files,you could adapt the loop shown there to perform the operation.

    while ((dir = readdir(d)) != NULL)
    {
        printf("%s\n", dir->d_name);
        if (/*Check whether file has the .jpg extension or another test*/)
        {
            // perform your copy operation on the file
        }
    }