#include <stdio.h> // --> FILENAME_MAX
#include <string.h>
// Asks the user for the file name and tries to open it. If it fails, it keeps asking for new file names.
static FILE * OpenFile(const char * fileHint)
{
char fileName[FILENAME_MAX] = {}; // Initialize the array to empty
FILE * file = NULL;
while (!file)
{
printf("Please enter the name of the %s file (no extension): ", fileHint);
fgets(fileName, FILENAME_MAX - 5, stdin); // Leave 5 bytes from the maximum theoretical limit (FILENAME_MAX) for the ".txt" and the terminating zero
size_t length = strlen(fileName);
sprintf(fileName + length - 1, ".txt");
file = fopen(fileName, "r");
if (!file)
printf("Could not open file: %s\n", fileName);
}
return file;
}
// Compare the content of two files and print the matching characters on the same offset.
int main()
{
FILE * f1 = OpenFile("first");
FILE * f2 = OpenFile("second");
while (!feof(f1) && !feof(f2))
{
int c1 = fgetc(f1);
int c2 = fgetc(f2);
if (c1 == c2)
printf("%ld - %c\n", ftell(f1) - 1, (char)c1); // ftell(f1) - 1 is the correct offset in the file as fgetc already moved the pointer
}
return 0;
}
First file
First line