I have a program that iterates through files and subdirectories, reads them in, does something and then dumps that into a single output file. I did this with the Win32 API. Now my problem is, if the user designates an output file that is in the same directory as the one I'm working in, my file iteration routine will attempt to open that as well, and basically, you end up reading from and writing to the same file at the same time.
My question is, is there a native C function which allows you to check whether two files are the same (and I don't mean, do they have the same content, I mean, are they really the same file).
Here's the function I'm working on:
Code:
void recurseDirectories(char *root, char *ext, FILE* f_out, void (*callBack)(FILE* f_source, FILE* f_output), bool recurse = true)
{
flist list = { 0, 0, NULL };
HANDLE h;
WIN32_FIND_DATA info;
int i, i_dir_count = 0, count = 0;
h = FindFirstFile(ext, &info);
if (h != INVALID_HANDLE_VALUE)
{
do
{
//This is where I would like to put some kind of conditional
//statement which compares the output file and the current handle,
//and if it turns out that they're the same, then it would not add a file to the list.
if (!(strcmp(info.cFileName, ".") == 0 || strcmp(info.cFileName, "..") == 0))
{
addfile(&list, info);
}
} while (FindNextFile(h, &info));
if (GetLastError() != ERROR_NO_MORE_FILES) errormessage();
FindClose(h);
}
else
{
errormessage();
}
for (i = 0; i < list.num_entries; i++)
{
if (list.files[i].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
i_dir_count++;
}
else
{
FILE* f_in = fopen(list.files[i].cFileName, "rb");
if(f_in)
{
callBack(f_in, f_out);
fclose(f_in);
}
f_out->_base;
else
{
fprintf(stderr, "File %s could not be opened!\n", list.files[i].cFileName);
}
}
count++;
printf("%d\t%d\n", i, count);
}
if(recurse)
{
list.files = (WIN32_FIND_DATA *) realloc(list.files, i_dir_count * sizeof(WIN32_FIND_DATA));
for (i = 0; i < i_dir_count; i++)
{
char newroot[MAX_PATH];
sprintf(newroot, "%s\\%s", root, list.files[i].cFileName);
SetCurrentDirectory(list.files[i].cFileName);
recurseDirectories(newroot, ext, f_out, callBack, recurse);
SetCurrentDirectory("..");
}
}
free(list.files);
}
Now, I guess you could do this by passing the filename as well into this function, but what if the user actually designated a separate path for the output file and that a file in the current directory had the same name as the output file. Then it would be skipped, right? So I'm looking for an alternative solution.
Any help is appreciated.