I'm coding a program in which one of the tasks I need to complete is to store each line of a text file (the name of which is provided via command line) as a separate string for future manipulation.
I have two issues with my program.
The first is the problem of storing the string inside an array. When I assign an index of the array with the string, everything works fine. But as soon as I free() the string for allocation of another string, both strings get deleted.
userText[numStrings - 1] = currentString;
/* Both userText at index and currentString hold the same value at this point */
free(currentString);
/* Both userText at index and currentString are free'd */
It could be a simple thing that I'm not understanding, I'm still quite new to C.
The second problem I have, is that I have no clue how to loop until the end of the file. I know that feof() exists, but that's kind of pointless since it will only return true until AFTER the end of the file, so I will be looping once more.
Here's the code: note it won't run until you set some condition in the last do/while loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char** argv){
char** userText = NULL;
char* currentString = NULL;
int currentStringSize = 0;
int numStrings = 0;
FILE* fp = fopen(argv[1],"r");
do{
numStrings++;
currentStringSize = 0;
do{
currentStringSize++;
currentString = (char*)realloc(currentString, currentStringSize * sizeof(char));
fscanf(fp, "%c", ¤tString[currentStringSize - 1]);
}while(!(currentString[currentStringSize - 1] == '\n'));
currentString[currentStringSize - 1] = '\0';
userText = (char**) realloc(userText, numStrings * sizeof(char*));
for (int i = 0; i < numStrings; i++){
userText[i] = (char*) realloc(userText[i], currentStringSize * sizeof(char));
}
userText[numStrings - 1] = currentString;
free(currentString);
currentString = NULL;
} while (//the end of the file *insert code here*);
for (int i = 0; i < numStrings; i++){
free(userText[i]);
}
free(userText);
fclose(fp);
return 0;
}
Thank you for you help.