I have a homework task that requires me to process .txt files by scanning them into a flexible data structure and then searching the files for words with capital letters. I'm having issues scanning them in this flexible data structure I'm using. The reason that the data structure needs to be flexible is that it needs to be able to process any .txt files.
The data structure I want to use is an array that points to arrays that contains the content of the line. I'm open to using a different structure if it's easier.
I've tried to scan it in line by line using fgets, and using malloc to allocate just enough to store the line, but it doesn't seem to work.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STEPSIZE 100
int main()
{
FILE *inputFile;
//Opens the file in read mode
inputFile = fopen("testfile.txt", "r");
//Error message if file cannot open
if (inputFile == NULL)
{
printf("Unable to open file");
return 1;
}
int arrayLen = STEPSIZE;
// Allocate space for 100 lines. The **lines is the data structure used to store all the lines
char **lines = (char **)malloc(STEPSIZE * sizeof(char*));
char buffer[3000];
int i = 0;
while (fgets(buffer, 3000, inputFile))
{
//Checks if the array is full, and extends it
if(i == arrayLen)
{
arrayLen += arrayLen;
char ** newLines = realloc(lines, 200 * sizeof(char*));
if(!newLines)
{
printf("cant realloc\n");
}
lines= newLines;
}
// Get length of buffer
int lengthOfBuffer = strlen(buffer);
//Allocate space for string. The +1 is for the terminating character
char *string = (char *)malloc((lengthOfBuffer + 1) * sizeof(char));
//copy string from buffer to string
strcpy(string, buffer);
//Attach string to data structure
lines[i] = string;
//Increment counter
i++;
printf("%s", lines[i]);
}
//Closes the file
fclose(inputFile);
for (int j = 0; j < 100; j++){
printf("%s \n", lines[i]);
}
return 0;
}
When the final for loop runs, ideally the contents of the file gets printed, just to show that it has been stored and is able to be processed, but currently i get exit code 11.
Any help would be appreciated.