0

I have a function to dynamically allocate and read a .txt file in C. However according to my assignment instructions the reading of the file should use strdup and not malloc to handle the dynamic memory allocation. I have tried tinkering with the strdup function to get it working, but I have yet to succeed. Here is the current working code using malloc. (NOTE: for my project I am reading 2 .txt files hence why in the main there are two of everything. Putting this to avoid any confusion.)

EDIT 1: using #include sys/stat.h for the stat struct

EDIT 2: Since there are lots of people asking, I am required to use strdup for the dynamic memory allocation. I will not show the instructions but it is explicitly demanded.

//Function that reads .txt input files
char* readInputFile(FILE* targetFile, struct stat stringBuffer)
{           
    char *tempString=malloc(stringBuffer.st_size+1);      
    fread(tempString, 1, stringBuffer.st_size, targetFile);     
    tempString[stringBuffer.st_size] = '\0';     
    fclose(targetFile);     
    return tempString;
}

int main(int argc, char *argv[])
{ 
    struct stat stringBuffer1; 
    struct stat stringBuffer2;
    stat(argv[1], &stringBuffer1); 
    stat(argv[2], &stringBuffer2); 
    FILE *wordListFile1 = NULL, *wordListFile2 = NULL, *outputFile = NULL; 
    wordListFile1=fopen(argv[1], "r");
    wordListFile2=fopen(argv[2], "r");
    char* fileString1;
    char* fileString2;
    fileString1 = readInputFile(wordListFile1,stringBuffer1);
    fileString2 = readInputFile(wordListFile2,stringBuffer2);
    ...
}
DegaClaw
  • 37
  • 4

0 Answers0