Reputation: 1
Trying to read the parent directory from a FAT12 floppy disk. I can currently read and print the contents of the files in the parent directories and traverse into the subdirectories and print their content if they are and ASCII file. The problem is that when reading files from subdirectories that are ASCII their contents print twice. I want to see how to counter this problem. Do I have to use a different structure of recursion? Here is the function right now:
void readDirectory(int fd, off_t dir_offset) {
// Seek to the directory table
lseek(fd, dir_offset, SEEK_SET);
uint16_t cluster_number;
char entry[DIR_ENTRY_SIZE];
ssize_t bytesRead;
while ((bytesRead = read(fd, entry, DIR_ENTRY_SIZE)) == DIR_ENTRY_SIZE) {
// Check if the entry is not empty and not a volume label
if (entry[0] != 0x00 && entry[0] != 0x2E && entry[11] != 0x0F) {
// Extract filename
char filename[MAX_FILENAME_LENGTH + 1];
strncpy(filename, entry, MAX_FILENAME_LENGTH);
filename[MAX_FILENAME_LENGTH] = '\0';
// Check if the entry is marked as deleted
if ((unsigned char)entry[0] == 0xE5) {
printf("\nDeleted File: %s\n", filename);
} else {
// Print filename and attributes
if (entry[11] & 0x10) { // Check if it's a directory
printf("\nDirectory: %s\n", filename);
// Extract starting cluster for subdirectory
cluster_number = *((uint16_t *)&entry[26]);
// Calculate offset for subdirectory based on cluster number
off_t sub_dir_offset = calculateClusterOffset(cluster_number);
// Read contents of subdirectory recursively
readDirectory(fd, sub_dir_offset);
} else {
printf("\nFilename: %s\n", filename);
printf("Attributes: 0x%02X\n", entry[11]);
printf("Size: %hu\n", *((uint16_t *)&entry[28]));
printf("Start Cluster: %u\n", *((uint16_t *)&entry[26]));
cluster_number = *((uint16_t *)&entry[26]);
// File is an ASCII file, print its contents
off_t file_offset = calculateClusterOffset(cluster_number);
uint16_t file_size = *((uint16_t *)&entry[28]);
printf("ASCII contents:\n");
printFileContents(fd, file_offset, file_size, cluster_number);
}
}
} else if (entry[0] == 0x00) {
// End of directory marker
break;
}
// Update the file offset to point to the next directory entry
dir_offset += DIR_ENTRY_SIZE;
lseek(fd, dir_offset, SEEK_SET);
}
if (bytesRead == -1) {
perror("Error reading directory entry");
}
}
I have all of the correct output it's just that every file from a subdirectory is printed twice. Also would like to just understand why this is happening so I can avoid it in the future.
Upvotes: 0
Views: 29